Reputation:
Web api 2, at the moment this is how we handle POST, PUT. I don't know if that is the best way, because not having the id in the body of the PUT request is bad? I have validations on the request body, should I validate the id seperately?
[HttpPost]
[Route("api/people")
public IHttpActionResult CreatePerson(PersonRequest request)
{
}
[HttpPut]
[Route("api/people/{id:int}")]
public IHttpActionResult UpdatePerson(int id, PersonRequest request)
{
}
public class PersonRequest
{
public string Name;
public string LastName;
}
How would you do that?
Upvotes: 0
Views: 122
Reputation: 18265
Your routing seems absolutely right to me.
You are right about PUT
requests: it is always better to include the resource identifier in the URI. What I would also do is to include it inside the resource representation (the request body), so you may further verify that the user intentions are really to update that specific resource (you should check if id
from the URI equals id
from the body).
For your POST
method I suggest you to return the entire resource representation (including the id
inside the body), but you do not need to require the user adding an id
inside the POST
request body (it could be null
, 0
, or even missing) if you are assigning it server-side.
Upvotes: 1
Reputation: 1772
Peter: my comments about your design:
1) Id should be included in class PersonRequest
2) so for Create action it should be 0, because it's new object and it will get "next Id value" from DB
3) for Update you need to check if Id > 0 and Id exists in system (in database), else throw exception.
Your new class:
public class PersonRequest
{
public int Id;
public string Name;
public string LastName;
}
4) I would rename class PersonRequest to Person.
Upvotes: 1