Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST: Updating multiple records

I need to update multiple records using a single HTTP request. An example is selecting a list of emails and marking them as 'Unread'. What is the best (Restful) way to achieve this?

The way I doing right now is, by using a sub resource action

PUT http://example.com/api/emails/mark-as-unread

(in the body)

{ids:[1,2,3....]}

like image 428
Tharaka Avatar asked Feb 06 '14 23:02

Tharaka


2 Answers

It a bit complicated to get array of models into an action method as argument. The easiest approach is to form a json string from your client and POST all that to the server (to your action mehtod). You can adopt the following approach

Say your email model is like this:

public class Email
{
    public int EmailID {get; set;}
    public int StatusID {get; set;}
    // more properties
}

So your action method will take the form:

public bool UpdateAll(string EmailsJson)
{
    Email[] emails = JsonConvert.DeserializeObject<Emails[]>(EmailsJson);
    foreach(Email eml in emails)
    {
        //do update logic
    }
}

Using Json.NET to help with the serialization.

On the client you can write the ajax call as follows:

$.ajax({
    url: 'api/emailsvc/updateall',
    method: 'post',
    data: {
        EmailsJson: JSON.stringify([{
            ID: 1,
            StatusID:2,
            //...more json object properties.
            },
            // more json objects
            ])
        },
    success:function(result){
        if(result)
            alert('updated successfully');
    });
like image 83
deostroll Avatar answered Oct 12 '22 13:10

deostroll


Create an algorithm-endpoint, like

http://example.com/api/emails/mark-unread

bulk-update is an algorithm name, a noun. It gets to be the endpoint name in REST, the list of ids are arguments to this algorithm. Typically people send them as URL query arguments in the POST call like

http://example.com/api/emails/mark-unread?ids=1,2,3,4

This is very safe, as POST is non-idempotent and you need not care about any side effects. You might decide differently and if your bulk update carries entire state of such objects opt for PUT

http://example.com/api/emails/bulk-change-state

then you would have to put the actual state into the body of the http call. I'd prefer a bunch of simple algo like mark-unread?ids=1,2,3,4 rather than one monolithic PUT as it helps with debugging, transparent in logs etc

like image 35
Igor Katkov Avatar answered Oct 12 '22 11:10

Igor Katkov