Search code examples
apirestidempotent

How to build REST API with server-defined ids?


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?


Solution

  • 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.