Using slug values and parameters in APIs allows more ‘hackable’ and easier to recall URIs to resources and helps Developer Experience (DX), i.e. API UX.
For example, in a Books API, the resource representing the book “Invisible Man” would have a slug equal to “invisible-man” in addition to its numeric canonical ID.
Slugs should be unique; they can be computed by many library routines widely available, which involves removing punctuation, lower-casing and replacing whitespace by hyphens.
This ability lets us access specific objects much more easily.
For example, we can use:
GET /api/books/invisible-man
In addition to:
GET /api/books/4456234
Both are valid requests for the object:
{ "id": "4456234", "slug": "invisible-man", "title": "Invisible Man", "author": "Ralph Ellison" }
An API is usually up and running at least in three environments: Dev, Staging and Production, and sometimes more.
With slug values identifying objects, a client need not know or discover IDs in different environments. For example in the books API, we can access the same object’s different versions across environments with /books/invisible-man, e.g. on different hosts such as api.dev.books.com/books/invisible-man or api.books.com/books/invisible-man.
The actual IDs in the underlying databases need not be known; a slug value lets us quickly access the resource’s copy in any environment.
Further, slug values for collection objects can be even more powerful. For example, exploring entire categories of books can be much easier if slug values for categories can be used:
GET /categories/novels/books
Instead of a specific ID-based request:
GET /categories/5423/books
In both cases the result is a list of all books in the category novels.
A frontend app using the API need not know the ID of a category to request objects in the category.
This means the app can make an API call by slug based directly from parsing the web URL, without having determine any resource IDs.
Consequently, slugs are ideal for URL paths for web apps, providing a correspondence between user URLs and API parameters for developers.
If a single object can have multiple kinds of slugs, we can use fields like titleSlug and categorySlug.