API design: Why you should use links, not keys, to represent relationships in APIs

Click for: original source

An article by Martin Nally from Google about how expressing relationships is very important in APIs. The most common way that API developers express relationships is to expose database keys, or proxies for them, in the fields of the entities they expose.

However, at least for web APIs, that approach has several disadvantages over the alternative: the web link. Standardized by the Internet Engineering Task Force (IETF), you can think of a web link as a way of representing relationships on the web.

Links can appear in API resources too, and using them instead of foreign keys significantly reduces the amount of information that has to be separately documented by the API provider and learned by the user.

A link is an element in one web resource that includes a reference to another resource along with the name of the relationship between the two resources.

Web link example

Source: https://cloud.google.com

The article then explains:

  • Representing relationships using foreign keys
  • Representing relationships using links
  • Caveats with relationships using links
  • What’s the best way to write links in JSON?
  • What’s the difference between an attribute and a relationship?

Replacing all the database keys with links is a fairly simple change and it significantly simplifies the API and reduces the coupling of the client and the server. The server is now free to change the format of new URLs at any time without affecting clients (of course, the server must continue to honor all previously-issued URLs).

Excellent!

[Read More]

Tags apis web-development google code-refactoring json restful