To build a REST API with Node.js and Express, create an Express app, define routes for each resource using HTTP methods (GET to read, POST to create, PUT or PATCH to update, DELETE to remove), validate input, store data in a database, return JSON with correct status codes, and add authentication, error handling and tests. These same steps scale from a weekend project to a production backend.

What is a REST API, in plain terms?

An API lets one program talk to another. A REST API exposes resources (students, courses, submissions) at URLs, and clients use HTTP methods to act on them. A mobile app or React frontend calls GET /api/courses to list courses and POST /api/enrolments to enrol. REST is popular because it uses plain HTTP, works with any language and is easy to cache and debug. If you're weighing alternatives, the main one is GraphQL, where clients ask for exactly the fields they need.

How do HTTP methods map to actions?

MethodRouteActionSuccess status
GET/api/coursesList courses200 OK
GET/api/courses/:idGet one course200 OK (404 if missing)
POST/api/coursesCreate a course201 Created
PATCH/api/courses/:idUpdate some fields200 OK
DELETE/api/courses/:idRemove a course204 No Content

How do you set up the project?

  1. Install Node.js (a current LTS version) and create a folder; run npm init -y.
  2. Install Express: npm install express.
  3. Create app.js: const express = require('express'); const app = express(); app.use(express.json());
  4. Add a health route: app.get('/health', (req, res) => res.json({ ok: true }));
  5. Start the server: app.listen(3000); and visit http://localhost:3000/health.

Organise code by responsibility as it grows: routes/ for URL definitions, controllers/ for request handling, models/ for data access, and middleware/ for shared checks.

How does middleware work?

Express processes each request through a chain of middleware functions with the signature (req, res, next). Each can read or change the request, send a response, or call next() to pass it on. JSON parsing, logging, authentication, rate limiting and error handling are all middleware. Understanding this chain is the key to understanding Express.

How do you validate input?

Never trust data from clients. Check types, required fields, lengths and formats before using them, and return 400 Bad Request (or 422) with a clear message when validation fails. Libraries such as express-validator, Joi or Zod make rules declarative. Validation protects your database from bad data and is your first line of defence against injection attacks.

How do you connect a database?

With PostgreSQL, use a client library or an ORM; with MongoDB, the official driver or Mongoose. Rules that apply to both: use parameterised queries (never build SQL by concatenating user input), keep connection settings in environment variables, create indexes for fields you filter on, and handle "not found" explicitly with a 404. Read MongoDB vs PostgreSQL to choose.

Which status codes should you use?

CodeMeaningWhen
200 / 201 / 204SuccessRead, created, deleted
400 / 422Bad requestInvalid input
401UnauthenticatedMissing or invalid login
403ForbiddenLogged in but not allowed
404Not foundResource doesn't exist
409ConflictDuplicate email, version clash
429Too many requestsRate limit exceeded
500Server errorUnexpected failures (log them)

How do you add authentication?

Hash passwords with bcrypt or Argon2, never store them in plain text. After login, either create a server-side session (stored in a database or Redis, referenced by a secure cookie) or issue a signed token such as a JWT. Then check authorisation on every request: a student may read their own submissions but not someone else's. Our comparison of JWT vs session authentication explains the trade-offs.

How should errors be handled?

Add a final error-handling middleware with four arguments (err, req, res, next). It should log the full error on the server and send the client a safe, consistent JSON response without stack traces or internal details. In Express 5, errors thrown in async route handlers reach this middleware automatically; in older versions you need to catch them and call next(err).

How do you test an API?

Use a tool like Postman or curl while developing, then write automated tests: start the app in a test mode with a test database, send requests, and assert on status codes and response bodies. Test the unhappy paths too: invalid input, missing auth, someone else's resource. Automated tests let you change code confidently and run in a CI pipeline on every push.

What does production readiness require?

A production checklist: items covered at each stage of this tutorial
Routes & status codes2/8
+ validation & database4/8
+ auth & error handling6/8
+ tests & deployment8/8

Counted from the eight sections of this guide.

Before going live: environment variables for secrets, HTTPS, security headers, CORS configured for your frontend only, rate limits on login and other sensitive routes, structured logging, health checks and a process manager or container. Deploy with Docker to a cloud service, and add monitoring.

How should you design good API URLs?

  • Use nouns for resources (/api/courses), and let HTTP methods supply the verbs.
  • Nest only for clear ownership: /api/courses/42/lessons is fine; deep nesting quickly becomes awkward.
  • Paginate lists with ?page= and ?limit= (or cursors) and return the total count.
  • Filter and sort with query parameters: ?city=Pune&sort=-createdAt.
  • Version the API (/api/v1/…) once external clients depend on it.
  • Return consistent shapes: the same error format everywhere, and predictable field names.

How do you document an API?

An API that nobody can understand doesn't get used. The OpenAPI specification (formerly Swagger) describes every endpoint, its parameters, request body and responses in a machine-readable file, and tools turn it into interactive documentation where frontend developers can try requests in the browser. Even for a personal project, a short README listing endpoints with example requests and responses makes the project far more impressive to anyone reviewing your portfolio, and it forces you to notice inconsistencies in your own design.

What mistakes do beginners make with Express APIs?

  • Forgetting to return after sending a response, which leads to "headers already sent" errors.
  • Trusting IDs from the client without checking that the logged-in user owns the resource.
  • Leaking stack traces or database errors in responses.
  • Hard-coding secrets such as database passwords or API keys in source files.
  • Returning everything: sending password hashes or internal fields because the whole database row was returned.
  • No pagination on list endpoints, which works in testing and breaks with real data.

Each of these is easy to avoid once you know it, and each is a favourite topic in code reviews and backend interviews. Writing a test for the unhappy path of every endpoint catches most of them before your users do, and it's a habit that marks you out as someone who builds software professionally rather than just getting demos to work.

What should you build next?

Connect a React frontend, add real-time updates with WebSockets, and serve a machine learning model behind your API (see deploying models with FastAPI). Program Zero's full-stack course covers Node.js and Express REST APIs, auth with JWT and OAuth2, WebSockets and system design, with a REST + React app, a real-time chat and a feed app as projects.