Creating with POST
Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 2 of 20.
POST adds an item to a collection. It goes to the collection's URL, because the client does not know the new id: the server picks it. The answer is 201 Created, with the new item as JSON and a Location header that holds the new item's URL. A header is a named line of text sent before the body.
var nextId = 8;
app.MapPost("/api/books", (BookInput input) =>
{
var book = new Book(nextId++, input.Title, input.Author);
books.Add(book);
return Results.Created($"/api/books/{book.Id}", book);
});The record parameter is read from the JSON body, and a missing property gets its type's default. A counter gives each book its id. Never make ids with Random or the clock: the same requests must give the same ids. Here that matters twice over, because every Send replays your earlier requests on a fresh app.
Challenge
EasyLet clients add tasks.
- In
Program.cs, below the list of tasks, add a counter:var nextId = 4; - At the bottom of the file, below
TaskItem, declare the body's shape:record TaskInput(string Title, bool Done); - Map
POST /api/taskswith aTaskInput inputparameter. Make aTaskItemfromnextId++,input.Titleandinput.Done, add it totasks, and answerResults.Created($"/api/tasks/{task.Id}", task).
The body { "title": "Order new chairs" } answers 201 with the header Location: /api/tasks/4 and:
{ "id": 4, "title": "Order new chairs", "done": false }Try it: press Run, choose POST, keep the path /api/tasks, type the body above and Send: 201, and the Headers tab shows Location: /api/tasks/4. Send GET /api/tasks/4: the new task. Send the same POST again: this one gets id 5, because the column replays the first POST before it.
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.MapGet("/api/tasks/{id:int}", (int id) =>
{
var task = tasks.Find(t => t.Id == id);
return task is null ? Results.NotFound() : Results.Ok(task);
});
app.Run();
record TaskItem(int Id, string Title, bool Done);
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST