How to build REST API with server-defined ids?

2.5k Views Asked by At

This is a classic RESTful way of creating resources I have in the application:

# This creates user. Client is responsible to create UUID, which is simple
PUT /users/CLIENT_GENERATED_UUID
# Access user by uuid
GET /users/UUID

When we touch the field of data storage performance it turns out that randomly generated UUIDs do not serve well by many reasons like data locality.

Server-generated IDs are good for performance but they don't really match REST:

  1. If you use POST to create resources, you lose idempotency: PUT, GET, DELETE idempotency is implied by REST, while POST is not.
  2. You may ask server to provide you with a nice ID before doing PUT. Despite it feels quite heavy and non-obvious, it also does not protect from dummy client that uses own random id instead of asking for it.

Could somebody give me a hint in this architecture matter?

3

There are 3 best solutions below

0
On BEST ANSWER

Creating a resource using is not meant to be idempotent. If the server assigns the ID, it must choose a different ID for every resource to be created. Such an operation must not be idempotent, repeating it must create a different resource.

Using POST against a collecton resource as in

POST /users

is totally RESTful if the server assigns the ID. This request can be repeated and it will create a different resource.

Using an idempotent operation like PUT for creating a resource only makes sense if the problem domain allows the client to control the ID. I think that is ist not true for most domains.

My advice: use POST and let the server assign the ID.

2
On

Actually when you read RESTful Best Practices you can find that:

The POST verb is most-often utilized for creation of new resources.

in addtion to:

PUT can also be used to create a resource in the case where the resource ID is chosen by the client instead of by the server.

0
On

In REST environment you send POST to create resources and can return the server generated ID to send the values after with PUT or PATCH.

POST /users
PUT /users/id

Also, people create resources with PUT using client generated IDs

PUT /users

But I think the best aproach is use server generated IDs with POST.

Here are a clear explanation: http://www.restapitutorial.com/lessons/httpmethods.html