Client side id generation strategy for REST web service
Asked Answered
L

1

6

Let's say I want to build a REST service for making notes that looks something like this:

GET    /notes/     // gives me all notes
GET    /notes/{id} // gives the note identified by {id}
DELETE /notes/{id} // delete note

PUT    /notes/{id} // creates a new note if there is no note identified by {id}
                   // otherwise the existing note is updated

Since I want my service to be indempotent I'm using PUT to create and update my notes, which implies that the ids of new notes are set/generated by the Client.

I thought of using GUIDs/UUIDs but they are pretty long and would make remembering the URLs rather dificult. Also from a database perspective such long string ids can be troublesome from a performance point of view when used as primary key in big tables.

Do you know a good id generation strategy, that generates short ids and of course avoids collisions?

Lamont answered 4/4, 2012 at 18:42 Comment(0)
D
9

There is a reason why highly distributed system (like , , etc.) use long UUIDs/hashes while centralized relational databases (or for that matter) can simply use ints. There is no easy way of creating short ids on the client-side in a distributed fashion. Either the server handles them or you must live with wasteful ids. Typically they contain encoded timestamp, client/computer id, hashed content, etc.

That's why REST services typically use

POST /notes

for non-idempotent save and then use the output of Location: header in response:

Location: /notes/42
Deppy answered 4/4, 2012 at 18:48 Comment(3)
Ok. But how can you avoid duplicate creation in case of a lost response?Lamont
@Zounadire: you can't (well, I believe there are some tricks). Note that plain soap does not guarantee that as well.Deppy
@TomaszNurkiewicz Hei Tomasz, can you share some of these tricks ? Example article to read and so on. When using client side generated ID it is prettey easy to deal with lost responses but how to deal with it when the id is generated server side ?Schappe

© 2022 - 2024 — McMap. All rights reserved.