Start learning free

LESSON 15 OF 173 · BACKEND: YOUR FIRST API

More Routes in TypeScript

Practice

An API has many paths, and each path has its own function. When a request arrives, Express compares its path with the path of each route, and calls the function of the route that matches. So /products/count is not /products: it needs a route of its own.

A route can answer any object as JSON. For example, a shop could tell its opening hours like this:

app.get("/hours", (req: Request, res: Response) => {
  res.json({ open: 9, close: 18 });
});

To answer how many items an array has, use .length instead of writing the number yourself: the answer stays right when items are added or removed. A path that no route matches, like /contact, gets 404 Not Found: Express has no function to call.

Your app must answer:

GET /products/count  →  200  {"count": 4}
GET /about           →  200  {"name": "Corner Shop", "currency": "USD"}
GET /contact         →  404  (an HTML error page)
GET /products        →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}, … all 4 products]
GET /                →  200  Welcome to the shop!

Your task: add two routes. GET /products/count answers the number of products as {"count": …}, computed with products.length. GET /about answers the shop's name, "Corner Shop", and its currency, "USD".


Assignment
Follow the Coding Tutorial to add the /products/count and /about routes.


Hint
Each new route has the same shape as the others: app.get with its path and a function that takes req: Request and res: Response. Put each object inside res.json(...).


STEP 1 OF 4
    Ctrl + Enter to check

    Shop More Routes in TypeScript

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free