简体   繁体   中英

REST API upsert endpoint vs create and update endpoints

I'm writing a REST API that among the rest deals with creating/updating/deleting users.

What will be the best practice to write create/update users endpoints?

  1. One endpoint that deals with both create and update (=upsert) users POST requests.
  2. Two different endpoints - one that deals with create users POST requests and the other that deals with update users PATCH requests.

There's a lot of wrong assumptions here. With REST, an endpoint represents a 'thing' not an 'action'.

Lets say that this thing is a user. You might host a user under a uri such as:

http://example.org/users/roy

From here, all the actions become natural. Want to delete the user?

DELETE /users/roy

Want to update it?

PUT /users/roy

Want to retrieve it?

GET /users/roy

Note that PUT is generally considered more RESTful than PATCH. It's a good idea to implement PUT if you are strictly going for REST. I think the distinction and benefits of PUT vs PATCH are a bit off-topic for question.

Now you're left with one more action... how do you create new users? Well, I would sum up the best practice as follows:

If you can allow the client to determine the URI, you should probably use PUT.

PUT /users/roy - Should respond with a 201.

If you want to ensure that you really create a new user and not overwrite an old one, you can let the client use the If-None-Match: * header to force the server to reject the request if the resource already exists.

I will say that the above is a best practice, but it's not the most common. Commonly rest services are backed by some relational database, and instead of natural keys, integers are often used in URIs.

This means that your url patterns look like

/users/1234

It also means that the client can't know what the URI will be when creating a new resource. The typical workaround to this is to NOT use PUT for creating, but use some kind of collection resource and use POST to create a new user:

POST /users/

A good API probably returns a Location header that has the uri to the newly created resource. A good client will know that whenever it receives a Location header after a non-safe method, it should clear its cache of that uri.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM