Node.js Intermediate: Express, Validation, SQLite and Tests
REST APIs with Express
In this lesson you will
- Create an Express app with GET and POST routes
- Use route parameters and send correct status codes
- Test the API from code with fetch
Introduction
Express is the most widely used web framework for Node. It adds routing, body parsing and a middleware system on top of the http module you already know. This lesson builds a small to-do API. The code is shown for reading, and the outputs come from a real run with Express 5.
Install it in a project with npm install express.
A minimal app
What is new compared with plain http:
app.get(path, handler)andapp.post(path, handler)match the method and path for you.:idin a path is a route parameter, available asreq.params.id(always a string, so convert it).express.json()is middleware that parses JSON bodies intoreq.body.res.json(...)sets the content type and sends JSON.res.status(201)sets the status.
Designing the API
A REST-style API uses nouns for resources and HTTP methods as verbs:
| Request | Meaning |
|---|---|
GET /todos | List todos |
GET /todos/2 | Get one todo |
POST /todos | Create a todo |
PATCH /todos/2 | Update part of a todo |
DELETE /todos/2 | Remove a todo |
Return 201 Created with a Location header for new items, 404 when something does not exist, and 400 when the client sends bad input.
Quick quiz
What does the :id in the route /todos/:id represent?
Testing it from code
This script starts the app on a free port and calls it. The outputs are from a real run (with the validation lesson's later checks left out):
200 [ { id: 1, title: 'Learn Node', done: false } ]
404 { error: 'Todo not found' }
201 /todos/2 { id: 2, title: 'Write tests', done: false }Order matters
Express checks routes in the order you define them. Put specific routes before general ones, and put error handlers last. Express 5 also catches errors thrown inside async handlers and passes them to your error handler, which older versions did not.
What this version lacks
The code above trusts req.body.title. If a client sends nothing, or a number, or a huge string, the data is bad. Data lives only in memory, so it disappears when the server restarts. The next lessons fix both problems.
Try it yourself
Add DELETE /todos/:id that removes a todo and returns 204 with no body, or 404 if it does not exist. Test all three outcomes with fetch.
Summary
- Express adds routing, parameters and body parsing to Node's http server.
- A REST API uses resources and methods, with 201 for created, 400 for bad input and 404 for missing items.
- Test your API from code, and remember that routes match in order.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading