Building a REST API with Node.js and Express

By Published 8 min read

Building a REST API with Node.js and Express

Introduction:

Almost every modern app, whether it’s a website, a mobile app or a dashboard, talks to a backend through an API. When the frontend shows a list of products, saves a form or deletes a comment, it sends an HTTP request to the API and gets JSON back. The most common style for these APIs is REST.

In earlier lessons we learned what Node.js is and what Express is. In this lesson we will put them to work and build a complete REST API for a small book library, step by step: listing, reading, creating, updating and deleting books, with validation, pagination, middleware and proper error handling. Every endpoint was tested with curl using Express 5 on Node.js 22, and the outputs shown are the real ones.

What Is a REST API?

REST (Representational State Transfer) is a set of conventions for designing APIs over HTTP. The main ideas are:

  • Everything is a resource (books, users, orders), identified by a URL such as /api/books or /api/books/42.
  • You act on resources with standard HTTP methods.
  • Data is usually sent and received as JSON.
  • Each request is stateless: it carries everything the server needs, such as an authentication token, so any server behind a load balancer can handle it.
  • Responses use meaningful HTTP status codes.

For our books resource, the endpoints look like this:

  • GET /api/books: list books
  • GET /api/books/:id: get one book
  • POST /api/books: create a book
  • PUT /api/books/:id: replace a book
  • PATCH /api/books/:id: update some fields of a book
  • DELETE /api/books/:id: delete a book

These are the four CRUD operations (Create, Read, Update, Delete). Notice that the URLs use nouns (/books), not verbs (/getBooks, /deleteBook): the HTTP method already says what to do.

The Status Codes You Need

  • 200 OK: success, with data in the response.
  • 201 Created: a new resource was created (after POST).
  • 204 No Content: success, with nothing to return (after DELETE).
  • 400 Bad Request: the client sent invalid data.
  • 401 Unauthorized / 403 Forbidden: not logged in / not allowed.
  • 404 Not Found: the resource doesn’t exist.
  • 500 Internal Server Error: something broke on the server.

Setting Up the Project

mkdir books-api
cd books-api
npm init -y
npm install express

We’ll organise the code into three files:

books-api/
├── package.json
└── src/
    ├── server.js        -> starts the server
    ├── app.js           -> creates the Express app and middleware
    └── routes/
        └── books.js     -> all /api/books endpoints

Keeping app.js separate from server.js is a good habit: tests can import the app without starting a real server.

Step 1: The App and the Server

// src/app.js
const express = require("express");
const booksRouter = require("./routes/books");

const app = express();

app.use(express.json()); // parse JSON request bodies

// A tiny request logger
app.use((req, res, next) => {
  const start = Date.now();
  res.on("finish", () => console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - start}ms`));
  next();
});

app.get("/api/health", (req, res) => res.json({ status: "ok" }));
app.use("/api/books", booksRouter);

// 404 for unknown routes
app.use((req, res) => res.status(404).json({ error: `Cannot ${req.method} ${req.path}` }));

// Central error handler (4 arguments)
app.use((err, req, res, next) => {
  if (err.type === "entity.parse.failed") return res.status(400).json({ error: "Invalid JSON" });
  console.error(err);
  res.status(500).json({ error: "Something went wrong" });
});

module.exports = app;
// src/server.js
const app = require("./app");

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`API running on http://localhost:${PORT}`));

Let’s go through app.js:

  • express.json() is middleware that reads the request body and, if it is JSON, puts the parsed object in req.body. Without it, req.body would be undefined.
  • The logger is our own middleware: it runs for every request, and when the response is finished it prints the method, URL, status code and time taken.
  • app.use("/api/books", booksRouter) mounts the books router, so every route in it starts with /api/books.
  • The last two app.use calls handle requests that matched no route (404) and any errors (500).

Step 2: The Books Router

For this tutorial we keep the books in an array. In a real app you would read and write a database such as MongoDB or MySQL here, but the routes would look exactly the same.

// src/routes/books.js
const express = require("express");
const router = express.Router();

// In-memory "database" for this tutorial
let books = [
  { id: 1, title: "Clean Code", author: "Robert C. Martin", year: 2008 },
  { id: 2, title: "The Pragmatic Programmer", author: "Andrew Hunt", year: 1999 },
];
let nextId = 3;

function validateBook(body) {
  const errors = [];
  if (typeof body.title !== "string" || body.title.trim() === "") errors.push("title is required");
  if (typeof body.author !== "string" || body.author.trim() === "") errors.push("author is required");
  if (body.year !== undefined && !Number.isInteger(body.year)) errors.push("year must be a whole number");
  return errors;
}

// GET /api/books?author=hunt&page=1&limit=10
router.get("/", (req, res) => {
  let result = books;
  if (req.query.author) {
    const q = req.query.author.toLowerCase();
    result = result.filter((b) => b.author.toLowerCase().includes(q));
  }
  const page = Math.max(1, parseInt(req.query.page) || 1);
  const limit = Math.min(100, Math.max(1, parseInt(req.query.limit) || 10));
  const start = (page - 1) * limit;
  res.json({ data: result.slice(start, start + limit), page, limit, total: result.length });
});

// GET /api/books/:id
router.get("/:id", (req, res) => {
  const book = books.find((b) => b.id === Number(req.params.id));
  if (!book) return res.status(404).json({ error: "Book not found" });
  res.json(book);
});

// POST /api/books
router.post("/", (req, res) => {
  const errors = validateBook(req.body || {});
  if (errors.length) return res.status(400).json({ errors });
  const { title, author, year } = req.body;
  const book = { id: nextId++, title: title.trim(), author: author.trim(), year };
  books.push(book);
  res.status(201).location(`/api/books/${book.id}`).json(book);
});

// PUT /api/books/:id  (replace the whole book)
router.put("/:id", (req, res) => {
  const index = books.findIndex((b) => b.id === Number(req.params.id));
  if (index === -1) return res.status(404).json({ error: "Book not found" });
  const errors = validateBook(req.body || {});
  if (errors.length) return res.status(400).json({ errors });
  const { title, author, year } = req.body;
  books[index] = { id: books[index].id, title, author, year };
  res.json(books[index]);
});

// PATCH /api/books/:id  (change only some fields)
router.patch("/:id", (req, res) => {
  const book = books.find((b) => b.id === Number(req.params.id));
  if (!book) return res.status(404).json({ error: "Book not found" });
  const allowed = ["title", "author", "year"];
  for (const key of allowed) {
    if (req.body && req.body[key] !== undefined) book[key] = req.body[key];
  }
  res.json(book);
});

// DELETE /api/books/:id
router.delete("/:id", (req, res) => {
  const index = books.findIndex((b) => b.id === Number(req.params.id));
  if (index === -1) return res.status(404).json({ error: "Book not found" });
  books.splice(index, 1);
  res.status(204).end();
});

module.exports = router;

Run the server:

$ node src/server.js
API running on http://localhost:3000

Now let’s test each endpoint with curl.

Step 3: Reading Books (GET)

$ curl localhost:3000/api/books
{"data":[{"id":1,"title":"Clean Code","author":"Robert C. Martin","year":2008},{"id":2,"title":"The Pragmatic Programmer","author":"Andrew Hunt","year":1999}],"page":1,"limit":10,"total":2}

$ curl localhost:3000/api/books/2
{"id":2,"title":"The Pragmatic Programmer","author":"Andrew Hunt","year":1999}

$ curl -i localhost:3000/api/books/99
HTTP/1.1 404 Not Found
{"error":"Book not found"}

req.params.id holds the :id part of the URL. It is always a string, which is why we compare with Number(req.params.id). A common bug is comparing "2" === 2, which is always false.

Step 4: Filtering and Pagination

Lists can grow to thousands of items, so a list endpoint should never return everything at once. Our GET /api/books reads query parameters from req.query to filter by author and to split results into pages:

$ curl "localhost:3000/api/books?author=hunt"
{"data":[{"id":2,"title":"The Pragmatic Programmer","author":"Andrew Hunt","year":1999}],"page":1,"limit":10,"total":1}

Returning page, limit and total alongside the data lets the frontend show “Page 1 of 5” and next/previous buttons. Notice that limit is capped at 100, so no client can ask for a million rows in one request. With a database you would pass the filter, LIMIT and OFFSET to the query instead of slicing an array, and add an index on the filtered column.

Step 5: Creating a Book (POST)

$ curl -i -X POST localhost:3000/api/books \
    -H "Content-Type: application/json" \
    -d '{"title":"Refactoring","author":"Martin Fowler","year":1999}'

HTTP/1.1 201 Created
Location: /api/books/3
{"id":3,"title":"Refactoring","author":"Martin Fowler","year":1999}

The response uses status 201 Created, returns the new book with its ID, and sets a Location header pointing to the new resource. The Content-Type: application/json header is important: without it, express.json() doesn’t parse the body.

Step 6: Validation

Never trust data from the client. Our validateBook function checks the input and the route returns 400 Bad Request with a list of all problems, so the frontend can show them next to the right form fields:

$ curl -i -X POST localhost:3000/api/books \
    -H "Content-Type: application/json" -d '{"title":""}'

HTTP/1.1 400 Bad Request
{"errors":["title is required","author is required"]}

And if the body isn’t valid JSON at all, express.json() throws an error that our error handler turns into a clean 400 instead of a crash:

$ curl -i -X POST localhost:3000/api/books \
    -H "Content-Type: application/json" -d '{bad json'

HTTP/1.1 400 Bad Request
{"error":"Invalid JSON"}

For larger projects, libraries such as Zod or Joi let you describe the expected shape of the data once and validate it in one line.

Step 7: Updating a Book (PUT and PATCH)

  • PUT replaces the whole resource. The client sends every field, and the route validates it like a new book.
  • PATCH changes only the fields that are sent. Our route copies only the allowed fields, so a client can’t overwrite the id or sneak in unexpected properties.
$ curl -X PATCH localhost:3000/api/books/1 \
    -H "Content-Type: application/json" -d '{"year":2009}'

{"id":1,"title":"Clean Code","author":"Robert C. Martin","year":2009}

Step 8: Deleting a Book (DELETE)

$ curl -i -X DELETE localhost:3000/api/books/2
HTTP/1.1 204 No Content

204 No Content means “done, nothing to send back”. Deleting the same book again returns 404, because it no longer exists.

Step 9: Middleware and Error Handling

Middleware is a function that runs between the request arriving and the route handling it. It receives req, res and next, and either sends a response or calls next() to pass control on. Middleware runs in the order you add it with app.use(), which is why express.json() comes first and the 404 and error handlers come last. Authentication, logging, CORS and rate limiting are all usually written as middleware.

The server’s log shows our logger middleware at work:

GET /api/books 200 4ms
GET /api/books/99 404 0ms
POST /api/books 201 1ms
POST /api/books 400 1ms
PATCH /api/books/1 200 0ms
DELETE /api/books/2 204 0ms
GET /api/nothing 404 1ms

An error handler is middleware with four arguments: (err, req, res, next). Express sends any error thrown in a route to it. In Express 5, this also works for async routes: if an await inside a route rejects, the error goes to your error handler automatically. We tested it with a route that throws after an await:

app.get("/boom", async (req, res) => {
  await new Promise((r) => setTimeout(r, 10));
  throw new Error("Database is down");
});

// Response: 500 {"error":"Something went wrong"}

(In Express 4 you had to wrap async routes in try...catch and call next(err) yourself, or the request would hang.)

Notice that the error handler logs the real error on the server but sends the client only a generic message. Never send stack traces or database errors to the client: they can reveal details an attacker could use.

Best Practices Checklist

  • Use nouns and HTTP methods: DELETE /api/books/7, not POST /api/deleteBook?id=7.
  • Return the right status codes and a consistent JSON error format, such as { "error": "..." }.
  • Validate every input and whitelist the fields a client may change.
  • Paginate lists and cap the page size.
  • Version your API (/api/v1/books) so you can make breaking changes later without breaking existing apps.
  • Keep secrets in environment variables, never in code (the PORT above is a simple example).
  • Add authentication (for example JWT tokens) before exposing endpoints that change data.
  • Handle errors centrally and log them on the server.

Conclusion:

A REST API exposes resources at URLs and uses HTTP methods for the CRUD operations: GET to read, POST to create, PUT and PATCH to update and DELETE to remove, with status codes such as 200, 201, 204, 400 and 404 to describe the result. With Express you parse JSON with express.json(), group endpoints in a Router, validate input, paginate lists, and finish with a 404 handler and a central error handler. The same structure scales from this in-memory example to a real database-backed API.

In the next backend lesson we will add authentication with JWT to this API, so only logged-in users can create, update and delete books.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume