ASP.NET Core Web API Interview Question #16
When should a Web API return 201 Created?
Web API & REST Fundamentals, Controllers, HTTP Methods & Status Codes Junior Beginner
Quick Interview Answer
201 Created is appropriate when a request successfully creates a new resource. The response should normally identify the URI of the newly created resource, commonly through the Location header.
Detailed Explanation
201 Created is appropriate when a request successfully creates a new resource. The response should normally identify the URI of the newly created resource, commonly through the Location header.
ASP.NET Core's CreatedAtAction and CreatedAtRoute helpers make it convenient to return the created representation together with a route to the new resource.
Code Example
[HttpPost]
public async Task<IActionResult> Create(
CreateProductRequest request)
{
var product = await _service.CreateAsync(request);
return CreatedAtAction(
nameof(Get),
new { id = product.Id },
product);
}