REST API Design — Best Practices with Node.js

Design and build RESTful APIs with Node.js: resource naming, HTTP methods, status codes, pagination, and versioning.

Node.js Intermediate 📖 10 min

RESTful Resource Naming

// Good: noun-based, plural
GET    /api/users          // List users
GET    /api/users/123      // Get user 123
POST   /api/users          // Create user
PUT    /api/users/123      // Update user 123
DELETE /api/users/123      // Delete user 123

// Nested resources
GET /api/users/123/posts    // Posts by user 123
POST /api/users/123/posts   // Create post for user 123

Complete CRUD API

const express = require('express');
const router = express.Router();

// GET all users with filtering
router.get('/', async (req, res) => {
  const { page = 1, limit = 20, sort = '-createdAt' } = req.query;
  const users = await User.find()
    .sort(sort)
    .skip((page - 1) * limit)
    .limit(Number(limit));
  
  const total = await User.countDocuments();
  res.json({
    data: users,
    pagination: { page: Number(page), limit: Number(limit), total }
  });
});

// POST create
router.post('/', async (req, res) => {
  const user = await User.create(req.body);
  res.status(201).json(user);
});

// PUT update
router.put('/:id', async (req, res) => {
  const user = await User.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true
  });
  if (!user) return res.status(404).json({ error: 'Not found' });
  res.json(user);
});

// DELETE
router.delete('/:id', async (req, res) => {
  const user = await User.findByIdAndDelete(req.params.id);
  if (!user) return res.status(404).json({ error: 'Not found' });
  res.status(204).send();
});

Status Codes

  • 200 OK — Successful request
  • 201 Created — Resource created
  • 204 No Content — Successful deletion
  • 400 Bad Request — Invalid input
  • 401 Unauthorized — Authentication required
  • 403 Forbidden — Insufficient permissions
  • 404 Not Found — Resource doesn't exist
  • 500 Internal Server Error

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →