DEV Community

Bipon Biswas
Bipon Biswas

Posted on

Create a REST API in Node.js

To create a REST API in Node.js, you will need to use a web framework such as Express.js. This framework provides a simple and flexible way to create a REST API that can handle HTTP requests and responses.

Here is an example of how you can create a simple REST API in Node.js using the Express.js framework:

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

// Create a route for the API
app.get('/api/products', (req, res) => {
  // Get the list of products from the database
  const products = getProductsFromDB();

  // Send the list of products as a response
  res.json(products);
});

// Start the server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

In this example, the app.get method is used to create a route for the API that handles GET requests to the /api/products endpoint. When a request is received, the API retrieves a list of products from the database and sends it back as a JSON response.

To make this API more complete, you can add additional routes for other HTTP methods, such as POST, PUT, and DELETE, to handle creating, updating, and deleting products. You can also add more endpoints to the API to support different resources, such as users, orders, etc.

With this approach, you can create a simple REST API in Node.js that can be used to access and manage data in your application.

Oldest comments (0)