Start learning free

LESSON 14 OF 173 · BACKEND: YOUR FIRST API

Send JSON

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.

In JSON, a list is written in [ ], and an object, like a C# dictionary, in { }, as pairs of a key and a value. Text goes in double quotes; numbers don't. In ASP.NET, Results.Json(...) turns a C# list or dictionary into a JSON response:

app.MapGet("/colors", () => {
    var colors = new List<string> { "red", "green", "blue" };
    return Results.Json(colors);
});

This route answers the JSON list ["red", "green", "blue"], and tells the client the answer is JSON. C# writes the list with { }, but the JSON answer uses [ ]. Each product's keys come out in your dictionary's order. Another server might send them in another order, and that's fine: programs find a value by its key, not by its place.

The products list 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 with app.MapGet for /products, whose function takes no parameters and returns the whole products list as JSON with Results.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 with the new path, but write () => { and a body, closed by });. Inside, pass the list to Results.Json(...) and return what it gives back.


STEP 1 OF 2
    Ctrl + Enter to check