</>
Skip to content
Node.js lessons (32/44)

Node.js — REST API

Basic REST Server

const http = require('http');

const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' }
];

const server = http.createServer((req, res) => {
    if (req.url === '/api/users' && req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(users));
    }
});

server.listen(3000);

RESTful Endpoints

MethodEndpointAction
GET/api/usersList all
GET/api/users/:idGet one
POST/api/usersCreate
PUT/api/users/:idUpdate
DELETE/api/users/:idDelete

With Express

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

app.use(express.json());

// GET all users
app.get('/api/users', (req, res) => {
    res.json(users);
});

// GET one user
app.get('/api/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ error: 'Not found' });
    res.json(user);
});

// POST create
app.post('/api/users', (req, res) => {
    const user = { id: users.length + 1, ...req.body };
    users.push(user);
    res.status(201).json(user);
});

app.listen(3000);

Mini Practice

  1. Build a REST server
  2. Implement CRUD operations
  3. Handle errors
  4. Add validation

Up Next

Continue with Web Server — serving static files.

Related Topics

Frequently Asked Questions about REST API

What is REST API in Node.js?

REST API is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn REST API?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn REST API.

Why is REST API important in Node.js?

REST API is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.