Start learning free

LESSON 14 OF 173 · BACKEND: YOUR FIRST API

Send JSON in JavaScript

Practice

A browser shows pages to people, but an API answers other programs: a phone app, a website's code, another server. Those programs may be written in any language, so they need the data as text, in a format they all read. That format is JSON.

JSON looks a lot like JavaScript: a list is written in [ ], and an object in { }, as pairs of a key and a value. Keys and text go in double quotes; numbers don't. In Express, res.json(...) turns a JavaScript array or object into a JSON response:

app.get("/colors", (req, res) => {
  const colors = ["red", "green", "blue"];
  res.json(colors);
});

This route answers the JSON list ["red", "green", "blue"], and tells the client the answer is JSON. When you run your code, the results show the keys of each object in alphabetical order, so "category" comes first. That's fine: programs find a value by its key, not by its place.

The products array is already in your file. Your app must answer:

GET /products  →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"},
                        {"id": 2, "name": "Notebook", "price": 7, "category": "office"},
                        {"id": 3, "name": "Lamp", "price": 29, "category": "home"},
                        {"id": 4, "name": "Pen", "price": 2, "category": "office"}]
GET /          →  200  Welcome to the shop!

Your task: add a route for /products with a function that answers with the whole products array as JSON.


Assignment
Follow the Coding Tutorial to add the GET /products route and send the product list as JSON.


Hint
Copy the shape of the route for "/", with the new path. Inside its function, pass the array to res.json(...).


STEP 1 OF 2
    Ctrl + Enter to check

    Shop Send Json in JavaScript

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