ASP.NET Core · Module 1 · Lesson 04 / 04

HTTP GET and your first JSON API

See how a web API returns structured data.

HTTP basics

An HTTP request has a method (such as GET or POST) and a path. A response has a status code (such as 200 for success or 404 for not found) and may have a body.

Return JSON from C#

Add this before app.Run() in your project:

app.MapGet("/api/course", () => new
{
    title = "Beginning ASP.NET Core",
    level = "Beginner",
    lessons = 5
});

Open /api/course in a browser. ASP.NET Core serializes the object into JSON.

Try query strings

Add:

app.MapGet("/greet", (string? name) =>
    $"Hello, {name ?? "friend"}!");

Visit /greet?name=Asha. Query parameters follow a question mark and can supply optional input.

Checkpoint

  1. What does GET usually ask the server to do?
  2. What is JSON useful for?
  3. What is the difference between /hello/Asha and /greet?name=Asha?
Answers

GET requests a resource; JSON is structured data commonly exchanged by APIs; the first example uses a route parameter while the second uses a query parameter.