Skip to main content

USE Create action to create a single resource

When building a RESTful API, creating a new resource typically involves using the HTTP POST method. This allows clients to send data to the API that can be used to create a new resource in the database.

To create a resource with HTTP POST in a REST API, clients must typically send a request to the API that includes the data necessary to create the resource. This data is typically sent in the form of a JSON or XML payload, which includes the resource's attributes and any related data.

Upon receiving the request, the API will typically validate the data and ensure that all required fields are present and in the correct format. If the data is valid, the API will create a new resource in the database and return a response that includes the resource's ID and any other relevant metadata.

While code block below seems very simple, there are a few constraints needs to be followed while developing a get endpoint. Let's follow what's been done in this example from a UsersController:

  • Name your method as CreateUser
  • Return a single object with type matching method name as in CreateUserResponse
  • Define an empty route as in [HttpPost("")]
  • Place appropriate ProducesResponseType attributes for each return type
  • Return 201 Created if User created successfully
  • Return ProblemDetails for errors
[HttpPost("")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ProblemDetails))]
[ProducesResponseType(StatusCodes.Status201Created, Type = typeof(CreateUserResponse))]
public async Task<IActionResult> CreateUser([FromBody] CreateUserRequest request)
{
CreateUserResponse response = new CreateUserResponse();
return Created(new Uri(response.Id, UriKind.Relative), response);
}

Never implement custom methods other than described 6 actions (Query, Get, Create, Update, Patch, Delete).