Start learning free

LESSON 23 OF 173 · BACKEND: YOUR FIRST API

Update a Product (PUT) in TypeScript

Practice

Prices change. To change a product that already exists, a client sends PUT to the product's own path, with the new version of the product in the JSON body. The server replaces the stored name, price and category with the ones it got. The id comes from the path, so it never changes.

A PUT route is written like the routes you know, with app.put. Here is a small one that replaces a value in an object settings (not part of the shop):

app.put("/settings", (req: Request, res: Response) => {
  const data = req.body;
  settings.theme = data.theme;
  res.json(settings);
});

req.body has the type any, so TypeScript lets you copy its values into the keys of a typed object. The shop holds many products, so your PUT first finds the one whose id is in the path, the same way the route that reads one product does. It answers the changed product with 200 OK, or 404 when no product has that id. The requests and answers your code must give, in this order:

PUT /products/2  {"name": "Notebook", "price": 9, "category": "office"}
  →  200  {"id": 2, "name": "Notebook", "price": 9, "category": "office"}
GET /products/2  →  200  {"id": 2, "name": "Notebook", "price": 9, "category": "office"}
PUT /products/4  {"name": "Blue pen", "price": 3, "category": "office"}
  →  200  {"id": 4, "name": "Blue pen", "price": 3, "category": "office"}
PUT /products/99  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  404  {"error": "Product not found"}
GET /products  →  200  [{"id": 1, "name": "Mug", …}, {"id": 2, "name": "Notebook", "price": 9, …}, {"id": 3, "name": "Lamp", …}, {"id": 4, "name": "Blue pen", "price": 3, …}]

Your task: add PUT /products/:productId. It reads the JSON body, finds the product with that id, sets its name, price and category to the values in the body, and answers the changed product. When no product has that id, it answers 404 with {"error": "Product not found"}.


Assignment
Follow the Coding Tutorial to add the PUT route that replaces a product's name, price and category.


Hint
The first lines are those of the DELETE route, with put in place of delete, and the loop is the one from the route that reads one product. Return the product inside the if, and send the 404 after the loop, so the 404 only runs when no product matched.


STEP 1 OF 12
    Ctrl + Enter to check

    Shop Update 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