Build Simple REST API With Node.js, Express And Mongoose

Prerequisites:

What is REST API?

Node.js:

Express.js:

  • It can be used to design single-page, multi-page and hybrid web applications.
  • It allows to setup middlewares to respond to HTTP Requests.
  • It defines a routing table which is used to perform different actions based on HTTP method and URL.
  • It allows to dynamically render HTML Pages based on passing arguments to templates.

Mongoose:

Build Simple REST API With Node.js, Express And Mongoose

Let’s start!

  • Create a new project folder and then run the following command in Command Line:
  • Install the dependencies listed above just like so:
package.json
  • Now create a file called server.js in your project directory and import express inside it.
Importing Express js
  • Now create an application called ‘app’, that inherit all features of express js, by adding the following code in the server.js file:
Inheritance
  • We need to introduce a middleware so our server recognizes the incoming request objects as JSON objects. For that, add the following piece of code in server.js file:
a middleware like body parser
  • Now, we need to listen for a connection to know that our server is running. You can do this by adding the following lines of code in your server.js file:
run the server on $port
  • Lastly, we must connect to mongodb using mongoose wrapper, so we need some lines of code in server.js file:
connect node.js with mongodb

Create simple HTTP Requests (get, post, update and delete):

HTTP Requests

Finally, server.js file must be something like this

server.js

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store