Start learning free

LESSON 20 OF 173 · BACKEND: YOUR FIRST API

Add a Product in TypeScript

Practice

Until now every route used GET, the method for reading. To send new data, a client uses POST. Express picks the function by the path and the method together, so GET /products and POST /products can go to two different functions.

A POST carries a request body, usually a JSON object. Express reads a JSON body only when you ask it to, with app.use(express.json()); near the top of the file; then req.body holds the body as a JavaScript object, with the TypeScript type any. When something new is stored, the answer has the status 201 Created, written like the 404: res.status with the number, then .json with the body. Here is the idea on another route:

app.use(express.json());

const messages: string[] = [];

app.post("/messages", (req: Request, res: Response) => {
  const data = req.body;
  messages.push(data.text);
  res.status(201).json({ count: messages.length });
});

The client doesn't choose the id: the shop gives the new product the largest id so far, plus 1, and stores it in products, so every route sees it. Your code must give, in this order:

POST /products  {"name": "Plant", "price": 15, "category": "home"}  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}
POST /products  {"name": "Stapler", "price": 9, "category": "office"}  →  201  {"id": 6, "name": "Stapler", "price": 9, "category": "office"}
GET /products/6  →  200  {"id": 6, "name": "Stapler", …}
GET /products?category=office  →  200  [{"id": 2, …}, {"id": 4, …}, {"id": 6, …}]
GET /products/count  →  200  {"count": 6}

Your task: add a POST /products route that reads the JSON body from req.body, gives the new product the next id, pushes it to products as a Product and answers it with the status 201. Turn on express.json() so Express reads the body.


Assignment
Follow the Coding Tutorial to build the POST /products route, from app.post to the 201 answer.


Hint
Find the largest id with a variable of type number that starts at 0, declared with let, and a loop that keeps the biggest id it has seen. Build the new product in newProduct with the type Product, not in product, and answer it with res.status(201) followed by .json.


STEP 1 OF 10
    Ctrl + Enter to check

    Shop Add Product 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