Mario Tacke
Mario Tacke

Reputation: 5488

Update multiple entities in one PUT request (or POST)

I am working on a website that allows clients to enter tabular information (merchants) into a grid. Each record can be identified by a unique id. I am trying to enable bulk updates through my Web API controller, instead of individual PUT requests. These requests are made through AJAX on the page (no post back/submit). Individual updates are working fine.

This is the code for individual updates:

// PUT api/Merchants/5
public HttpResponseMessage PutMerchant(int id, Merchant merchant)
{
    if (!ModelState.IsValid)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    }

    if (id != merchant.MerchantId)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    db.Entry(merchant).State = EntityState.Modified;

    try
    {
        db.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }

    return Request.CreateResponse(HttpStatusCode.OK);
}

What I would like to build is a similar PUT for bulk updates (something like this):

// PUT api/Merchants
public HttpResponseMessage PutMerchants(Merchant[] merchants)
{
    ...
}

Is this possible and does it follow RESTful conventions? Also, since some merchants should be updated and others created, do I use POST to split them up? How are these situations generally handled with Web API controllers?

Upvotes: 0

Views: 2915

Answers (1)

William Xifaras
William Xifaras

Reputation: 5312

Typically, HttpPost is for new records and HttpPut is for updating. Here is a really good stackoverflow answer on the differences between the two.

PUT vs POST in REST

That being said, you can pass in a list in either case:

   // PUT api/Merchants
    public HttpResponseMessage PutMerchants([FromBody]List<Merchant> merchants)
    {

    }

Upvotes: 1

Related Questions