Creating a RESTful API these days is not such a great challenge for a competent developer. But how about having one up and running in 10 minutes? Olatunde Garuba over at codementor.io shows you how to build a basic Node.js RESTful API with a Mongo database in 10 minutes.
You’ll be creating a toy list API with endpoints to read the list, add, edit and delete and task items.
Assuming you’ve got Node and Mongo installed already, the first step is to open the terminal and create a directory ‘toDoListAPI’. Then run ‘npm init’ to create a package.json file. In the JSON file, add details about your app, its name, the version and a little description etc. Then create a server.js file. Finally, create a new directory ‘api’ with three subdirectories, models, routes and controllers. Then add a toDoListController.js file to the controllers folder, a toDoListModel.js file to the models folder and toDoListRoutes.js to the routes folder.
The next step is to get your server up and running. For this, you’ll need to install express.js along with nodmon, which will keep track of code changes and restart the server accordingly. You’ll then have to add these packages as dependencies to your JSON file, remembering to add nodmon as the value of the ‘start’ key in the ‘scripts’ section. Finally, copy the following code snippet into server.js and start the server with ‘npm run start’.
Setting up the schema
Next, you’ll need to install Mongoose. This is a library that will let you interact with your Mongo db instance. Create a new file in the models folder toDoListModel.js and copy the following code snippet into it.
Setting up the routes
The following step is setting up routing for your endpoints. You’ll define just two routes. To do this, copy the following code snippet into todoListRoutes.js.
Setting up the controller
The obvious next step is to define those controller functions that you’re using for routing to the controller file. So create five functions: ‘read_a_task’, ‘create_a_task’, ‘update_a_task’, ‘delete_a_task’, ‘list_all_tasks’ that use Mongoose functions to access your db instance.
Putting everything together
The final steps are to add your database url to the Mongoose connection instance, load the created model ‘task’ and register the routes with the server. You might want to install BodyParser and use BodyParser parse as middleware before the handlers too. Finally start the Mongo server by running ‘mongod’ in the terminal.
Testing via Postman
The last thing you want to do is test that everything works as promised. For this, you’ll need Postman installed. Once it is, open Postman and type ‘http://localhost:3000/task’ in the request url section. For the same address, then choose the ‘post’ method, add ‘x-www-form-urlencoded’, enter the key ‘task’ and give it the value of the task you want to retrieve. Finally click send and if all’s well, you should see the relevant task that you created.