Sowmiya
Sowmiya

Reputation: 313

Partial fields update REST API

There is this MongoBean: SuperBean

class SuperBean extends MongoBaseBean{
     private String id;
     private String title;
     private String parent;

     //And getters, setters   
}

Need is to write an update API, which is capable of performing partial attributes update. Common approach seen across the web as well as heard from my peers is to check the fields in the request for Null and update if not null. But what if the update request is for the value to be updated to Null??

After few discussions, we came up with three approaches:

What factors should be considered to chose one of these approaches? Is there another better way to approach this problem?

Upvotes: 1

Views: 1069

Answers (1)

Spark.Bao
Spark.Bao

Reputation: 5763

In my projects, we usually choose the way that similar with your second way. but not exactly the same.

for example, in your client side, you have a page or a view to modify your profile info, includes name, birthday, gender, although you just modify the name value, when you click save button, it still will send the data to server includes birthday and gender with name field, but just keep its value as old. and the server API will directly update these three values in database, won't check whether its value changed or not.

if you have another page or view to modify other parts of the profile, likes password, it need add a new method in client and a new API in server. the API URL likes PATCH /reset_password, and the sent data should include old_password and new_password field.

PS:
1. we use PUT or PATCH to update a resource, not POST, POST is used to create a new resource. 2. when you update a resource, in the above example, the API likes PATCH /profiles/:id (other's profile) or PATCH /profile (yourself profile), so the sent data doesn't need id field anymore, it includes in your API URL.

Upvotes: 1

Related Questions