Menu

Building A RESTful API With Node.js And Express

Introduction:
In this blog, we will explore how to build a RESTful API using Node.js and Express, two popular tools in the JavaScript ecosystem.

Setting up the Project:

  1. Create a new directory for your project and navigate into it using the command line.
  2. Run npm init to initialize a new Node.js project. Follow the prompts to set up your project's details.
  3. Install the necessary dependencies by running npm install express and npm install body-parser.

Creating the Express Server

  1. Create a new file called index.js and open it in your preferred code editor.
  2. Import the required modules by adding the following lines at the top of the file.
    const express = require('express');
    const bodyParser = require('body-parser');

     

  3. Initialize the Express app and configure it to use body-parser for parsing JSON request
    const app = express();
    app.use(bodyParser.json());
    

Defining API Routes:

  1. Define the API routes for your application. For example, let's create a simple endpoint to retrieve a list of users. Add the following code after initializing the Express app:
    const users = [
      { id: 1, name: 'Abhi Singh },
      { id: 2, name: 'TemplateBench' }
    ];
    
    app.get('/api/users', (req, res) => {
      res.json(users);
    });
    
  2. You can also create routes for other CRUD operations like creating, updating, and deleting users. Feel free to expand upon this basic example based on your specific needs.

Starting the Server:

  1. Add the following code at the end of the index.js file to start the server on a specified port (e.g., 3000):
    const port = 3000;
    app.listen(port, () => {
      console.log(`Server running on port ${port}`);
    });
    
  2. Save the file and return to the command line. Run node index.js to start the server.

Testing the API:

  1. Open your web browser or an API testing tool like Postman.
  2. Navigate to http://localhost:3000/api/users retrieve the list of users.

 

Conclusion:

Now, We have created a rest Api in Node and Express. This is a small demo for the rest of the API. We generate more APIs by following these steps.
Thanks

914
Search

Ads