Menu
CoddyTech

Resources and URLs

Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 1 of 20.

Other programs call your API, so its URLs should be easy to guess. Most web APIs follow a style called REST: each URL names a resource, a thing the API stores, and the HTTP method says what to do with it.

GET    /api/invoices      the list of invoices
GET    /api/invoices/7    invoice 7
POST   /api/invoices      add an invoice
DELETE /api/invoices/7    remove invoice 7

Paths hold nouns, never verbs: with /api/getInvoice?id=7, every client must learn a new word for each action. The collection has a plural name, and one item is the collection's path plus its id.

app.MapGet("/api/invoices/{id:int}", (int id) =>
{
    var invoice = invoices.Find(i => i.Id == id);
    return invoice is null ? Results.NotFound() : Results.Ok(invoice);
});

{id:int} is a route parameter with a constraint: it matches whole numbers only, so /api/invoices/abc matches no route and answers 404. An id that matches no invoice answers 404 too, through Results.NotFound().

challenge icon

Challenge

Easy

In this section you build a task tracker API. It starts with three tasks and GET /api/tasks, which answers all of them. The tasks are TaskItem records, because .NET already has a type called Task. Add the URL for one task.

  1. In Program.cs, below GET /api/tasks, map GET /api/tasks/{id:int}.
  2. Find the task whose Id equals id with tasks.Find, and answer it with Results.Ok(task). GET /api/tasks/2 answers:
    { "id": 2, "title": "Book the meeting room", "done": true }
  3. When no task has that id, answer Results.NotFound(): status 404 with an empty body.

Try it: press Run. The column sends GET /api/tasks and shows the three tasks. Send GET /api/tasks/2: 200 and the task above. Send GET /api/tasks/99: 404. Send GET /api/tasks/abc: 404 as well, because {id:int} only matches numbers.

Try it yourself

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};

app.MapGet("/api/tasks", () => tasks);

app.Run();

record TaskItem(int Id, string Title, bool Done);
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in REST APIs