Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

RESTful API Development with Node.js

RESTful API Development with Node.js

Developing a RESTful API with Node.js involves creating endpoints that adhere to the principles of Representational State Transfer (REST). These endpoints handle HTTP methods (GET, POST, PUT, DELETE) to interact with resources. Here's a step-by-step guide to building a basic RESTful API using Node.js:

Step 1: Set Up Your Project

1. Create a new directory for your project and navigate into it:
 
mkdir my-api
cd my-api
 

2. Initialize the project and create a package.json file:

npm init -y
  

3. Install Express.js, a popular web application framework for Node.js:

npm install express
 

Step 2: Create the Server

Create a server.js file and set up the Express application:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json()); // Middleware to parse JSON requests

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
 

Step 3: Define Routes and Controllers

Define routes for different resources (e.g., users, products) and corresponding controllers to handle the logic:

// Create a 'controllers' directory and inside it, create a 'usersController.js' file:

// usersController.js
const users = [];

exports.getUsers = (req, res) => {
  res.json(users);
};

exports.createUser = (req, res) => {
  const { name, email } = req.body;
  const user = { id: users.length + 1, name, email };
  users.push(user);
  res.status(201).json(user);
};
 

Step 4: Set Up Routes in server.js

In server.js, import the controller and set up routes:

const { getUsers, createUser } = require('./controllers/usersController');

// GET all users
app.get('/users', getUsers);

// POST a new user
app.post('/users', createUser);
 

Step 5: Test Your API

Start the server:

node server.js
 

Use a tool like Postman or curl to send requests to your API. For example:

  • GET Request:

    URL: http://localhost:3000/users

  • POST Request (with JSON body):

    URL: http://localhost:3000/users
    Body: { "name": "John Doe", "email": "john@example.com" }
    Step 6: Expand and Refine
    Continue adding routes and controllers for different resources, and implement additional features like updating and deleting resources. You can also incorporate middleware for authentication, input validation, error handling, and more.