Building Production REST APIs - Complete CRUD, Status Codes & Query Filtering

Building a RESTful API (Representational State Transfer) is the most common use case for Node.js in industry. A well-designed REST API adheres to standard HTTP methods, clean resource-based URLs, strict input validation, and standardized JSON response envelopes.

RESTful URL Naming Conventions

HTTP Method Endpoint URL Action Description Expected Status Code
GET /api/courses Retrieve a paginated list of courses 200 OK
GET /api/courses/:id Retrieve details of a single course by ID 200 OK (or 404)
POST /api/courses Create a new course record 201 Created
PATCH /api/courses/:id Update specific fields of an existing course 200 OK
DELETE /api/courses/:id Delete a course record from database 204 No Content

Implementing Full CRUD in Express

const express = require('express');
const app = express();
app.use(express.json());

let courses = [
  { id: 1, title: 'Node.js Master Class', price: 49.99 },
  { id: 2, title: 'React JS Full Stack', price: 59.99 }
];

// 1. GET ALL (with Pagination & Filtering)
app.get('/api/courses', (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const maxPrice = parseFloat(req.query.maxPrice);

  let filtered = [...courses];
  if (!isNaN(maxPrice)) {
    filtered = filtered.filter(c => c.price <= maxPrice);
  }

  const startIndex = (page - 1) * limit;
  const paginated = filtered.slice(startIndex, startIndex + limit);

  res.status(200).json({
    success: true,
    page,
    totalRecords: filtered.length,
    data: paginated
  });
});

// 2. CREATE (POST)
app.post('/api/courses', (req, res) => {
  const { title, price } = req.body;

  if (!title || typeof price !== 'number') {
    return res.status(400).json({
      success: false,
      error: 'Validation Error: title (string) and price (number) are required'
    });
  }

  const newCourse = { id: courses.length + 1, title, price };
  courses.push(newCourse);

  res.status(201).json({ success: true, data: newCourse });
});

// 3. PARTIAL UPDATE (PATCH)
app.patch('/api/courses/:id', (req, res) => {
  const course = courses.find(c => c.id === parseInt(req.params.id));
  if (!course) return res.status(404).json({ success: false, error: 'Course not found' });

  if (req.body.title) course.title = req.body.title;
  if (req.body.price) course.price = req.body.price;

  res.status(200).json({ success: true, data: course });
});

// 4. DELETE
app.delete('/api/courses/:id', (req, res) => {
  const index = courses.findIndex(c => c.id === parseInt(req.params.id));
  if (index === -1) return res.status(404).json({ success: false, error: 'Course not found' });

  courses.splice(index, 1);
  res.status(204).send(); // 204 No Content
});

app.listen(3000);

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What are the core HTTP verbs used in REST APIs and their meanings?

GET (reads/retrieves resources), POST (creates a new resource), PUT (replaces an entire resource), PATCH (partially updates specific fields of a resource), and DELETE (removes a resource).

Q2. What is Idempotence in REST APIs?

An HTTP method is idempotent if executing it multiple times produces the identical server state as executing it once. GET, PUT, and DELETE are idempotent. POST is NOT idempotent, because submitting a POST request 5 times will create 5 separate records in the database.

Q3. Which HTTP status codes should you return in REST APIs?

200 OK (successful GET/PUT/PATCH), 201 Created (successful POST), 204 No Content (successful DELETE), 400 Bad Request (validation failure), 401 Unauthorized (missing/bad token), 403 Forbidden (insufficient permissions), 404 Not Found, 429 Too Many Requests, and 500 Internal Server Error.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

MongoDB & Mongoose ODM

Connect REST endpoints to persistent database collections.

JWT Auth & Password Hashing

Secure REST API routes with Bearer token authentication.

Testing with Jest & Supertest

Automate end-to-end integration tests for REST APIs.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!