Welcome...



...All those moments will be lost in time, like tears in rain....

- soliloquy from Blade Runner


Bits and bytes do get lost, awash in the rain of data flow that is Internet. They slip away from us, never to found again... some of them will be captured here, many more will not... like tears in rain...



Thursday, July 2, 2015

Post vs Put vs Patch in Web API

 Debates rages on and on. Why, when and how.
 My 2 cents:

  1. 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.
  2. 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.
  3. PATCH - intended for partial updates, not really available yet.
  4. 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