Debates rages on and on. Why, when and how.
My 2 cents:
So something like this for POST:
My 2 cents:
- POST- create if you don't know resource location, but leaving it to the server to determine it and send back location of new resource to you in the header.
- PUT - hm, it should really be called replace. It should either create resource on specified url (by client!) or completely update it, no partial updates here.
- PATCH - intended for partial updates, not really available yet.
- POST - update - tricky one. Since we don't have PATCH yet that's the only alternative for partial updates as of now.
So something like this for POST:
// POST: api/Items
[ResponseType(typeof(BudgetItem))]
public IHttpActionResult Post(BudgetItem item)
{
if (ModelState.IsValid)
{
_itemRepository.CreateItem(item);
return CreatedAtRoute("DefaultApi", new { id = item.Id }, item);
}
else
{
return BadRequest(ModelState);
}
}
And for PUT:
// PUT: api/Items/5
public IHttpActionResult Put(int id, BudgetItem item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
BudgetItem oldItem = _itemRepository.GetItem(id);
if (oldItem == null)
{
_itemRepository.CreateItem(item);
return CreatedAtRoute("DefaultApi", new { id = item.Id }, item);
}
else
{
_itemRepository.UpdateItem(item);
return Ok(item);
}
}
No comments:
Post a Comment