What should I return in an Httppost and Httpput in an API?

Asked

Viewed 331 times

1

I am doing an API in . NET Core and I have a question in what I should return in the methods Httppost and Httput, as below:

    // POST: api/Product
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] ProductDto product)
    {
        try
        {
            await _productAppService.Add(product);
            return Ok();
        }
        catch (Exception ex)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, ex);
        }
    }

    // PUT: api/Product/5
    [HttpPut("{id}")]
    public async Task<IActionResult> Put(Guid id, [FromBody] ProductDto product)
    {
        try
        {
            var success = await _productAppService.Update(id, product);
            return success ? Ok() : (IActionResult)NotFound();
        }
        catch (Exception ex)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, ex);
        }
    }

As you can see, when making a POST I simply return an OK and when making a PUT, if it finds the ID of a product, it returns OK, otherwise it returns Notfound.

Aiming at best practices, what would be necessary to return in these methods? Like a success flag and a newly stored model, or a simple OK is enough? or does it depend on the context in which we are working?

  • Take a look at this link: https://docs.microsoft.com/pt-br/azure/architecture/best-practices/api-design

2 answers

1


The Return type of an API is often neglected, despite having as much importance as any other part.

The return of each endpoint depends on what exactly is done by the API. In the case of a POST the most normal is to use the 201 Created (https://tools.ietf.org/html/rfc7231#Section-6.3.2) and include the Location of the newly created record. In your case it is easy to do this with the method CreatedAtAction.

In some cases, where the action is not immediately interpreted, the most correct is to use the 202 Accepted (https://tools.ietf.org/html/rfc7231#Section-6.3.3). This behavior is more common in more sophisticated systems, where the action is not interpreted by the API.

In the case of PUT it makes no sense to return a created, nor inform the entity’s URI, since it is already known. Thus, the most usual is to return the 204 No content (https://tools.ietf.org/html/rfc7231#Section-6.3.5). As in the POST, can also make sense to return the 202 Accepted.

Microsoft documentation is a good source of information on how to build an API with C#: https://docs.microsoft.com/en-us/aspnet/core/web-api/? view=aspnetcore-3.1

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.