DataBase

Building a Restful CRUD API with Node JS, Express, and MongoDB

Application Programming Interface is the abbreviation for API. An API is a software interface that enables two apps to communicate with one another. In other words, an API is a messenger that sends your request to the provider and then returns the response to you.


Creating the application

On your Desktop ( or any other place ) create a new folder named nodejs-api and open it in any Code Editor (for this Tutorial I am using VS Code). Once you done open terminal ( You can either use VS Code terminal or external terminal ) and run

This will generate a simple package.json and now we need to install some dependencies which we need. Fire up your terminal and run

Mongoose is an ODM (Object Document Mapping) tool for Node.js and MongoDB. It helps you convert the objects in your code to documents in the database and vice versa.

Evolution of the database

This will install Express ( for server ), Mongoose, and Body Parse for parsing data The body-parser middleware converts text sent through an HTTP request to a target format or in other words body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need

Now once everything is installed, we can start creating our web server.

Setting up the webserver

Create a new file named server.js in the root folder of the application and add the following code to it

  • First, we imported the dependencies which we need i.e Express and Body Parser
  • Second, Once we imported them we added body-parser middlewares using express’s app.use() method
  • Then, We defined a simple GET route that returns a message that the server is running.
  • Finally, we defined the port and listen to that port for incoming connections

Now in your terminal, run node server.js and go to http://localhost:8080 to access the route we just defined. and you should see

Connecting our application to MongoDB

In server.js import mongoose, just like the code below

and add the below code after it

finally, this is how your server.js should look like now

Defining the model in Mongoose

Now, in the root directory create a new folder named app and inside of it create another folder named models. Create a new file named app.model.js and add the following code inside of it This model contains one field that is message

Defining the routes

Now create a new folder called routes inside the app folder and add the following code inside of it.include the routes in server.js. Add the following require statement before app.listen() line inside server.js file.

Tags

Let's Talk

Do you want to learn more about how I can help your company overcome problems? Let us have a conversation.