POST
POST creates a new item from the JSON in the request body. The DAO inserts it and returns it with its new id, and the action answers 201 Created with CreatedAtAction, which also says where the new item lives. Invalid bodies get 400 automatically.
Journeyman · ASP.NET Core · REST API · Updated
After this lesson you can
- Write a POST action that adds an item from the body and answers 201 Created with CreatedAtAction
- Explain how [ApiController] answers 400 Bad Request by itself when the body breaks a validation rule
Key takeaways
- A
POSTto the collection's address creates an item. In an[ApiController], a parameter of a class type comes from the JSON body by itself. OUTPUT INSERTED.CategoryIdhands back the new id from theINSERT, and Dapper'sExecuteScalar<int>reads it.CreatedAtAction(nameof(GetById), new { id = added.CategoryId }, added)answers201 Createdwith the new item and aLocationheader.- When the body breaks a validation rule,
[ApiController]answers400 Bad Requestitself, and your action never runs. - That
400is a problem details response (application/problem+json): a standard JSON shape that lists the errors by field.
A client creates a new item with a POST to the collection's address, sending the new item as JSON in the body. The server saves it and answers with the saved item, now with its new id.
The DAO: insert, and get the new id
The database chooses the new CategoryId (it's an identity column). SQL Server's OUTPUT INSERTED.CategoryId hands it back from the INSERT itself, and Dapper's ExecuteScalar reads it:
public Category Add(Category category)
{
string sql = """
INSERT INTO Categories (CategoryName, Description)
OUTPUT INSERTED.CategoryId
VALUES (@CategoryName, @Description);
""";
using SqlConnection connection = new SqlConnection(connectionString);
category.CategoryId = connection.ExecuteScalar<int>(sql, category);
return category;
}
Passing category itself as the parameters works because its property names match @CategoryName and @Description.
The action
[HttpPost]
public ActionResult<Category> Add(Category category)
{
Category added = categoryDao.Add(category);
return CreatedAtAction(nameof(GetById), new { id = added.CategoryId }, added);
}
[HttpPost]answersPOST /api/categories.Category categoryis filled from the JSON body. In an[ApiController], a parameter of a class type comes from the body without being told. (You can write[FromBody] Category categoryto make it explicit.)ActionResult<Category>means "either aCategory, or a status code result". Returning ActionResult<T> covers it in full; here it lets the action returnCreatedAtAction(...).CreatedAtActionanswers201 Created, puts the new category in the body, and adds aLocationheader with the new category's address. It builds that address from theGetByIdaction and the route valuesnew { id = ... }, so it's always right, even if the route changes.
Restart the API, and send Add Snacks from your Insomnia collection again. The 405 Method Not Allowed from Insomnia: POST is now the answer you wrote down:
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: http://localhost:5179/api/categories/9
{
"categoryId": 9,
"categoryName": "Snacks",
"description": "Chips, nuts and pretzels"
}
The client now knows the new id, and the exact address to GET it from: the Location header is on the answer's Headers tab in Insomnia.
Bad bodies get 400 for free
Category has [Required] and [StringLength(15)] on CategoryName. Send Add a bad category, whose body breaks them:
{
"categoryName": "A name that is far too long",
"description": "Too long"
}
The answer:
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json; charset=utf-8
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"CategoryName": [
"The field CategoryName must be a string with a maximum length of 15."
]
}
}
Your action never ran. [ApiController] checked the annotations, found an error, and answered 400 Bad Request itself, listing every problem by field. In MVC you checked ModelState.IsValid and showed the form again; in an API, the client gets this list and shows it however it likes.
That body is a problem details response (application/problem+json): a standard JSON shape for errors, with a title, a status and, here, the errors. Clients everywhere know how to read it. (The response also carries a traceId, an id for finding this request in the server's logs.)
Do it: check a new category's name the way [ApiController] does
Before Add runs, [ApiController] checks the body against the annotations on CategoryName, [Required] and [StringLength(15)], and answers 400 with every error it finds. Write that check yourself, as a method.
The method gets one value:
categoryName: the new category's name from the body, astring. It's""when the body has no name.
For example, the body of Add a bad category:
| Rule | For "A name that is far too long" (27 characters) |
|---|---|
[Required]: the name isn't empty |
kept |
[StringLength(15)]: at most 15 characters |
broken |
So Errors("A name that is far too long") returns a list of one message: "The field CategoryName must be a string with a maximum length of 15."
Your job: write the method Errors(string categoryName) so it returns the error messages, a List<string>.
- When the name is empty (
""), the list holds"The CategoryName field is required." - When the name is longer than 15 characters, the list holds
"The field CategoryName must be a string with a maximum length of 15." - When the name breaks neither rule, the list is empty: the body is fine, and
Addwould run.
Practiced live on the lesson page: write the C# right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
POST is insert-and-tell: save the item, then answer 201 Created with the item and its address. Put validation rules on the model, and [ApiController] turns away bad requests before they reach your code.