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 7Paths 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
EasyIn 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.
- In
Program.cs, belowGET /api/tasks, mapGET /api/tasks/{id:int}. - Find the task whose
Idequalsidwithtasks.Find, and answer it withResults.Ok(task).GET /api/tasks/2answers:{ "id": 2, "title": "Book the meeting room", "done": true } - 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);
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST