Web Development · Intermediate level

Intermediate level · Module 4: Back-End Basics with Node.js and Express · Lesson 2 of 3

Building an API with Express

Create an Express server with routes, route parameters and middleware that returns JSON.

In this lesson you will

  • Create an Express app with routes and parameters
  • Use middleware for JSON parsing, logging and errors

Key concepts

Express approute handlerreq.params and req.querymiddleware

The lesson

Express is a minimal Node.js web framework. Install it with npm, create an app and define routes: app.get("/api/courses", (req, res) => res.json(courses));. Start the server with app.listen(3000).

Route parameters capture parts of the path: app.get("/api/courses/:id", …) reads req.params.id; query strings such as ?search=web arrive in req.query. Return 404 when a requested item does not exist.

Middleware runs for every request before the route: express.json() parses JSON bodies, a logger records requests and an error-handling middleware at the end turns unexpected errors into a safe 500 response.

Step by step

  1. Create an Express project with npm.
  2. Add GET routes for the course list and one course.
  3. Support a ?search= query on the list.
  4. Add JSON parsing and an error-handling middleware.

Practice activity

Implement the course endpoints of the training centre API.

Expected result: Both endpoints return correct JSON, search works and an unknown id returns 404.

Check your understanding

  1. How does Express read the :id part of a path?

    Show answer

    From req.params.id.

  2. What does express.json() do?

    Show answer

    Parses JSON request bodies into req.body.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.