Aspnetcore.docs: the put body should also include the ID

Created on 15 May 2018  Â·  8Comments  Â·  Source: dotnet/AspNetCore.Docs

The screenshot shows the following request body:
{
"name":"walk cat",
"isComplete":true
}

However, the Update method, given how it is written in this tutorial, requires the request body to contain the updated item's ID and requires it to match the id supplied in the URI. Sending the request such as shown on the Postman screenshot produces the BadRequest error.


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

P1 P2 Source - Docs.ms

Most helpful comment

PUT do not need id in the body because the id is in the url: https://localhost:44375/api/todo/1

Most likely you forgot to put the id in the url.

All 8 comments

I have the exact same problem...
Still can't fix it

@ThinkAwsome

Simply add the correct ID to the request body. Send something like this:

{
"id": 2,
"name":"walk cat",
"isComplete":true
}

Repleace 2 with the correct id of your item. Make sure it matches the id provided in the url you send the request to.

@gaazkam That was exactly the right thing to do to get my PUT working. The todo item is now updating. Thanks!

Alternatively, you can comment the check for ID in code as below
public IActionResult Update( long id, [FromBody] TodoItem item )
{
if ( item == null ) //|| item.Id != id )
...
...
so that you do not have to pass id in request body.

@sidpab I think I prefer that approach. cc @scottaddie

PUT do not need id in the body because the id is in the url: https://localhost:44375/api/todo/1

Most likely you forgot to put the id in the url.

@rosdi I believe the code of this post for the update method was changed, and now it doesn't check if the URI ID matches the ID in the body of the request.

How ever I still have a question: What is actually the best approach to specify the ID in only one place?

I see two options:

  • Include it only in the URI (Which seems more elegant). If so, what would be the best way to avoid having to find the item by the ID, and then update prop by prop of that object?
  • Include it only in the Body of the request.

What are your thoughts on this?

Please refer to this Microsoft REST API Guideline: https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design#define-operations-in-terms-of-http-methods

For POST (create new resource) the Id (if any) should be in the body.
For PUT (update existing resource) the Id should be in the URI.

The article can explain it better than me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

StevenTCramer picture StevenTCramer  Â·  3Comments

wgutierrezr picture wgutierrezr  Â·  3Comments

Rick-Anderson picture Rick-Anderson  Â·  3Comments

nenmyx picture nenmyx  Â·  3Comments

YeyoCoder picture YeyoCoder  Â·  3Comments