Creating Your First REST API in Node.js with Express.js: A Step-by-Step Guide

Creating a REST API in Node.js is a great way to build a scalable, high-performance web service. In this blog post, we will go over the steps of creating a simple REST API using Node.js and the Express.js framework.

First, make sure you have Node.js and npm (Node Package Manager) installed on your machine. You can download Node.js and npm from the official website.

Next, create a new project folder and initialize it with npm:

Copy codemkdir my-api
cd my-api
npm init -y

The npm init -y command will create a package.json file, which will keep track of all the dependencies for your project.

Now we will install Express.js, a popular web framework for Node.js that makes it easy to handle HTTP requests and routes. To install Express.js, run the following command:

Copy codenpm install express

In the main file of your project (e.g. index.js), import Express.js and create a new instance of it:

Copy codeconst express = require('express');
const app = express();

We can now define routes for our API using the app.get(), app.post(), app.put(), and app.delete() methods. For example, to handle a GET request to the root of the API, we can use:

Copy codeapp.get('/', (req, res) => {
  res.send('Hello World!');
});

The app.get() method takes two arguments, the first being the route and the second being a callback function that will handle the request. In this example, the route is the root '/' and the callback function sends a "Hello World!" response to the client.

Finally, we can start the server using the app.listen() method:

Copy codeapp.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});

The app.listen() method takes two arguments, the first being the port number on which the server will run and the second being a callback function that will be executed when the server starts. In this example, the server runs on port 3000.

You can now run the API by running node index.js in the terminal and test it by sending a GET request to localhost:3000 using a tool like Postman.

This is just a simple example of how to create a REST API in Node.js using Express.js. You can now add more routes and functionality to your API to create more complex web services.

In summary, creating a REST API in Node.js with Express.js is simple and straightforward. With just a few lines of code, you can have a fully functional web service up and running. Whether you're building a small personal project or a large enterprise application, Node.js and Express.js are powerful tools that can help you create robust and scalable web services.

Hope you like this. Thanks for reading.

Did you find this article valuable?

Support Ankit Mewada by becoming a sponsor. Any amount is appreciated!