Good URI Practices: nouns and verbs, ID types and requesting data formats

OpenMarket – July 6, 2020

by Vicente Martinez

Modeling Actions: Nouns vs Verbs. AKA “How to model actions?”

The URI Structure of an API should be as meaningful and predictable as possible. The idea is to have something that the user can understand.

An API is resource-centric: it deals with resources and with operations on those resources.

Operations (verbs) should be represented via HTTP verbs on resources. This way we work with the HTTP protocol and its semantics.

A verb in the URI is – always, always, always – a design smell

BAD: …/account/pay

When it comes down to a single verb, the URI semantic means that there is only 1 operation available to do in this URI, which is to “pay”. Since it is a verb, it also means that it is not the actual resource of the API. There is not a table in our database named “pay”. So, this entire URI is render useless for anything else than “pay”

BETTER: …/account/payment

When using a noun, it makes a representation of a relation in the URI. It means we can work with the resource instead of the action. We can set more than just 1 operation like the verb in this UIR, which is a better approach and makes more sense to the user. All operations related to this entity, can be done in a noun URI.

EVEN BETTER …/accounts/payments

Although both are simply fine, plurals over singulars are widely accepted.

To keep consistency, do not mix them in your URI architecture once you have made up your mind.

 

IDs vs UUIDs in URIs

IDS

PROS

CONS

SmallerIDs are less flexible than UUIDs (exposes underlying technology used)
No brainer, already availableIDs are guessable (susceptible to web crawlers and bots)

 

UUIDs

PROS

CONS

More flexible. (Migrating databases is less of a pain and won’t compromise URI architecture)Require more space in memory
Can’t be simply guessed. (Resistance to crawlers)Requires an initial setup

 

Representing DATA formats in a URL

Adding data representation in the URL is a terrible idea.

BAD: …/users/vicentem.json

EVEN WORSE: …/users/vicentem?format=json

The HTTP protocol already defines the semantics to ask different types of representation.

BETTER: Use the Accept (Accept-Language) headers

 

Further good URI practices

  • If there are 2 URIs for the same resource, send the canonical URI to the client.
  • Hyphens ( – ) are more usable than underlines ( _ ).
  • Use always lowercase

See all tech blog posts

Related Content