A Tour of the Express Starter: Routes, Requests and Responses
The Maple Street Pet Adoption Center's API is handed over, built with Express, and this lesson runs it and tours it, from npm start and its routes to req.params, req.query and req.body, res.json and status codes, ending at data/pets.js, the one file the database code goes in.
Apprentice · Node.js · REST API · Updated
After this lesson you can
- Explain how an Express route reads a request with req.params, req.query and req.body, and answers with res.json
- Choose the status code an API answers with, such as 200, 201, 400, 404 or 500
- Explain why the starter's routes only call data/pets.js, and find where its data code goes
Key takeaways
- npm start runs the API on your own computer at http://localhost:3100, and it keeps answering requests until Ctrl+C stops it.
- A route pairs a method and a path, such as GET /pets/2, with a function that reads the request (req) and answers with the response (res).
- req.params holds the named parts of the path, req.query the part after the question mark, and req.body the JSON a POST sends.
- res.json answers with JSON, and the status code says how it went, such as 200, 201, 400, 404 or 500.
- The routes only call the functions in data/pets.js, so that file is the one place the database code goes.
An API you're asked to work on is almost always someone else's code first: before you change a line, you run it, send it requests and find where each job lives. This lesson does that for the API the rest of this module builds on: the Maple Street Pet Adoption Center's. An API answers other programs, such as a website or a phone app, with data instead of pages. This one is built with Express, the most used web framework for Node.
Get it running
The API is this chapter's exercise code. Clone it into your mongodb-course folder, install its packages, and start it, in VS Code's terminal:
cd ~/mongodb-course
git clone https://github.com/ask-codey/exercise-mongodb-pet-api-warm-up.git
cd exercise-mongodb-pet-api-warm-up
npm install
npm start
> start
> node server.js
Maple Street's pet API is listening on http://localhost:3100
localhost is your own computer, and 3100 is the port, like an apartment number at that address, so several programs can listen at once. The API keeps waiting for requests until Ctrl+C stops it.
A route: a method, a path and what to do
Open http://localhost:3100/pets in your browser. The browser sends a request, GET /pets, and the API answers with all six pets as JSON, text written like the documents you know:
The code that answered is a route, in routes/pets.js:
petsRouter.get("/", async (req, res) => {
const pets = await listPets(req.query.species);
res.json(pets);
});
Read it as "when a GET request comes for this path, run this function". The method says what the caller wants: GET reads, POST adds. The path is "/" because app.js hands every address that starts with /pets to this file, with app.use("/pets", petsRouter), so "/" here means /pets. The function gets two objects: req, the request, like an order slip, and res, the response it fills in and sends back.
Reading the request: params, query and body
A request can carry values in three places, and Express puts each in its own spot on req:
| The request | Where the value is | In the route |
|---|---|---|
GET /pets/2 |
in the path, where the route says :id |
req.params.id is "2" |
GET /pets?species=cat |
after the ?, in the query string |
req.query.species is "cat" |
POST /pets with a JSON body |
in the body | req.body.name is "Waffles" |
Anything from an address is text, "2" and not 2, and a value that wasn't sent is undefined. Here's the route for one pet, which reads its :id (read "colon id"):
petsRouter.get("/:id", async (req, res) => {
const pet = await getPet(req.params.id);
if (pet === null) {
sendProblem(res, 404, `There's no pet ${req.params.id}.`);
return;
}
res.json(pet);
});
A browser's address bar only sends GET. For a POST, the starter's pets.http lists requests for VS Code's REST Client extension: in VS Code's Extensions view, search for REST Client (by Huachao Mao) and click Install. A Send Request link then appears above each request, and the answer opens beside it.
Answering: res.json and status codes
res.json(...) sends its value as JSON. Every answer starts with a status code, three digits that say how it went:
| Code | It means | In this API |
|---|---|---|
| 200 OK | It worked | GET /pets, GET /pets/2 |
| 201 Created | Something new was saved | POST /pets |
| 400 Bad Request | The caller sent something wrong | POST /pets with no name |
| 404 Not Found | There's nothing at that address | GET /pets/99, GET /snacks |
| 500 Internal Server Error | The server itself failed | an error inside a route |
Codes in the 400s are the caller's mistake; the 500s are the server's. res.json alone answers 200, and res.status(201).json(pet) picks another code. Every error answer has the same shape, built by sendProblem in problems.js:
POST /pets
HTTP/1.1 400 Bad Request
{"status":400,"title":"Bad Request","detail":"A new pet needs a name and a species."}
The files, and where the database code goes
server.jsstarts the app on port 3100.app.jsbuilds it withcreateApp(): it reads JSON bodies, sends/petsto the routes, and answers 404 for any other address and 500 for an error.routes/pets.jsholds the three routes.data/pets.jskeeps the pets, in an array for now, with the functionslistPets,getPetandaddPet.problems.jsholdssendProblem, andtest/holds the tests.
The routes never touch the pets themselves: they call a function in data/pets.js and await it. A restaurant works the same way: the waiters take orders and never cook, so the kitchen can get a new stove and the waiters won't notice. When the pets move into MongoDB in the next chapter, every line of database code goes in data/pets.js, and a route that only asks it for pets, such as GET /pets/2, stays exactly as it is. Two other files change a little, and neither talks to MongoDB: server.js connects to the database and hands it to the app as createApp(db), and the GET /pets route passes on two new choices the center's list page asks for, only pets that are good with kids, and a page number.

Three of those functions aren't finished, and the API shows it. http://localhost:3100/pets?species=cat gives back all six pets, dogs and rabbit too. /pets/2 can't find Mochi:
GET /pets/2
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's no pet 2."}
And adding Waffles with pets.http answers 500, while the terminal shows Error: addPet isn't built yet. Those three gaps are yours to fill in Exercise: Pet API Warm-Up.
Check yourself
2 questions to try on the lesson page.
So what
A route reads req.params, req.query or req.body, awaits one function in data/pets.js, and answers with res.json and the right status code. Knowing that path through the code is how you find your way around any Express API, and it tells you exactly where MongoDB goes next.