342 points · by sarego · 7y ago · 189 comments
> 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).
If you have to honor all previously-issued URLs then you aren't changing your format -- you are supporting two formats from now on, the old one and the new one.
You can of course tell your users that you will deprecate the old format, but unless you are as powerful as Google your users may prevent you from enforcing a deadline for deprecation.
If the URLs in your API responses are FQDNs rather than relative paths, all of this gets significantly harder to deal with.
Even if you figured all of that out, links are not idiomatic if your users consume your api via an RPC or GraphQL.
Stripe uses a date as its version and it maintains state for each user, so it knows whether to serve an old version or latest and greatest. They offer UI and tools to manually migrate to a new version, with clear expectations and changelogs provided. They can build a rollout and sunset plan around that.
Protobuf is append only until you change the actual package. This gives you the opportunity to make additive changes without making a breaking change and you don't need to maintain separate releases as you make incremental updates or bug fixes. If the API changes significantly, it's no longer the same API, it's a new one.
> Even if you figured all of that out, links are not idiomatic if your users consume your api via an RPC or GraphQL.
Agreed, although you could model a link in the object-based structure representation to match the protocol, something like..
# RPC
{
"rel": "owner",
"procedure": "GetOwner",
"args": {
"id": 98765
}
}
# GraphQL
{
"rel": "owner",
"root": "owner",
"args": {
"id": 98765
}
}Why is this true for non-user facing urls? Seems like an argument could be made that you only need to support the urls for as long as the response was cacheable.
In fact, links in responses are probably easier to update, because waiting for client software to upgrade can take a long time - but waiting for old versions to fall out of caches or at least dwindle to a small enough number is likely a much shorter wait.
Furthermore, when your clients are composing links based on keys, there's no good way for the server to tell a client that the uri has changed - the composition is in the client, and the key (presumably) hasn't changed, so the thing the server would want to update is out of conventional reach.
But with uri's there's at least a conventional solution - redirects. That's not going to be an ideal solution; but as a way of limiting transition pain it might have a place.
All in all, I think links are likely less painful to use than keys when it comes to uri routing changes. (But really, try to avoid changing uri's in the first place, because whatever you do it's likely going to be painful somewhere).
“A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types“
In this case the only URL that is support long term is the entry point into the application. All other resources are discoverable from the index.
Consider your audience. Is it APIs like GitHub? Well guess what, you're stuck with maintaining backwards compat anyway, may as well have the relationships readable.
And if it's not and you control both ends then what does it matter because you can break links all you want.
It was touched on but less emphasized the relationships being expressed as links exposes further context than you otherwise get.
It's also nice to be able reason about shared domains. I.e. you might have the concept of a stock item and an order item. They are both represent the same thing in the real world and share a lot of information but depending on the value of self will tell you what kind of data you can expect to be a available and what domain you're in as well. Reading logs would be oh so much clearer.
(1) There can be several levels of entity identifiers, that is the same entity exists at several levels where it has different identifiers. Example: a computer has DNS name and IP address (and MAC address); a person may have several identifiers. These (initially independent) spaces can be structured differently:
(1.1) Layered structure like DNS and IP (1.2) Independent, e.g., a person has two passports from different countries
(2) Links (representing relationships) are attributes. Like all attributes they are functions which map input entity identifiers into output (address) space identifiers.
Taking this into account, the problem is that URLs frequently play two roles, that is, one address convention is used at two layers simultaneously which can lead to numerous problems and controversies:
o URLs are used at access (protocol) level where the goal is to identify computers and access paths within some service (and not entity). For example, this layer has no idea what this means: http://service.com/passports/1234 - it is used for HTTP access only.
o URLs are used to identify real entities and here we re-use the previous name convention for higher level purposes by identifying people like http://service.com/passports/1234 although we do not care about protocols or computer names.
In order to avoid serious problems we need to follow these steps:
* Recognize and document that there are two independent address spaces
* Define a mapping between these two spaces. Initially, it can be identity relationship, that is, every entity name (URL) is mapped to the same URL used for access.
* If necessary (and frequently highly desirable) use relative names by assuming that the higher level segments of the name can be restored from the context or configured separately.
These rules are especially important for extensibility and for complex evolving systems where the standards and conventions change in time.
You don't have to honor it forever; if you want to be good about planning for changes, you annotate each link with the latest date when it is guaranteed not to be expired, and the latest date an updated authoritative URL will be available (either as content in the resource representation or an HTTP redirect) if it expires on the earliest possible date. Consumers are then free to determine whether they need to update links or whether the data from which they come is stale (if your resources at any given link are immutable but for metadata about currency and links to updated versions if the content of the logical entity has changed, so that you can always recover the same version of an entity you fetched at the original URL so long as the URL hasn't expired, clients don't even need to check each references URL for updates, they can just check the base URLs of the entities they already have read that referenced them, and in the process update all referenced URLs; you kind of need that allow clients an approximately consistent view of data when they can't read it all simultaneously anyway, and if your API doesn't need that level of consistency, it then it certainly doesn't need link stability, either—you’ver already decided you are dealing with fundamentally ephemeral data,.so.if people don't follow links relatively quickly, they aren't getting meaningful data even if the links are permanently stable.)
If I were paying someone for access to such an API, I would do everything in my power to change providers. Tracking link expiration would be a terrible developer experience. Such a thing may be a sound design for a system, but it's not a good design.
Providers like Twilio and Stripe have been largely successful because they've aimed for making developer experience as non-sadistic as possible.
What's different about this proposal? It would seem to acknowledge and support that type of activity directly, rather than through ad-hoc and kludge type mechanisms that typically include paying somewhat shady 3rd-party services.
It seems like any of these schemes make assumptions that some things are invariant when switching to a new version, so you don't have to start over.
For example, if user IDs are just integers then you have a fairly conservative assumption that clients can store the user IDs and they can be reused with a new version. That is, users won't be renumbered. But everything else about the API can change between versions.
A site-relative URL also fixes part of the URL template between versions, so it can be safely stored. But the host can change.
I'm skeptical that URL's are all that helpful here. Why not do a POST using something like protobufs and avoid the issue entirely? An API like this is site-specific anyway and requires custom client code (other than the parsing layer which can be generated from a schema). It seems weird to pretend otherwise, as if some universal client existed. At best, you could use a browser for debugging, but that's about it.
With HATEOAS, at the best case is that clients just bump the entry point url (or even have it bumped for them) and then follow the links they are given. It's not possible to upgrade clients that way if they are constructing urls themselves.
Instead, you could just use a database of redirects which you append to when you make format changes. For some applications, the overhead of maintaining a redirect service is far lower than trying to maintain support for multiple formats. (And this redirect service may even be something you need/want for other reasons.)
I've found more success in supporting two formats using the v2 api to serve the v1 one.
/people/12345 becoming /people/v2/12345
Sure, you still have to support the old version (maybe only temporarily), but migrating schemas gets marginally easier (you can do it via an entirely different service, for example)
If a client gets a 410 when following a stored link, they can always find the new url for the resource by following links from the parent resource (this is recursive, all the way back to the root url).
Conversely, I often need to log or store API-provided entity ids on my side, and having to parse it out of a URL or store irrelevant URL bytes in my own database would be really annoying.
You're not going to avoid the need to compile entity URLs on the client side either, unless you only make requests to entities returned by the API, which would be a weird constraint to design client code around.
I really don't see the point to any of this.
The validation would be intrinsic in the client side concatenation of the server address with the relative URI.
For example, the article includes URLs like "/people/123". The security of having a leading slash in these depends on API base URL.
"https://api.hotstartup.com/v1" – safe
"https://api.hotstartup.com" – unsafe with ".evil.com/people/123"
I wouldn't really call this particular scenario a security issue, but allowing such things is a bad habit that will eventually bite. It's like not HTML-encoding values like usernames that you "know" are safe (but you know are not HTML-encoded).
If all you stored was the ID, all you would need to change is the logic in your API client which accepts the ID and constructs the URL for it.
I also mentioned that I don't want to store redundant garbage in my logs and database, especially if I want to index the column containing that entity id.
More fundamentally, I think it's trying to solve a smaller problem in the face of a much bigger one, you still need to know what the response of any given endpoint is going to be. Just because they've passed me a link, doesn't me I don't need documentation on what endpoint that link points to. I still need to know that the owner is a link to the people endpoint so I can properly parse that result. That in turn requires just as much documentation (IMO) to describe the relationships as it would to properly document your URI templates.
Obviously, the primary reason to use links over ids is to give the developers of the API more control over changing things like routes and Ids and whatnot, but I feel like it is a bit disingenuous to make it out to be a much better user experience or something, since it really isn't.
...Its ludicrously bloated and part of the reason why no one does "real rest."
Actually, it doesn't need to. The owner object would only have invoice IDs. The invoice collection resource would be discoverable through the root endpoint through the same process used to discover the pet and owner collection resources.
In fact, the owner doesn't need to have any invoice information at all. The invoice collection endpoint can simply be queried to find an invoice related to the pet and/or owner.
> ...Its ludicrously bloated and part of the reason why no one does "real rest."
Actually it isn't, and the main reason why "no one does real rest" is because web API clients are required to perform content discovery, which is more complex than simply using hard-coded URLs/URL paths.
Of course this complexity is only apparent and superficial, as having to support a myriad of API versions ends up with a simple solution that due to all the technical debt that piles on rather quickly is far more complex and error-prone and unmaintainable than the approach required to do REST.
> web API clients are required to perform content discovery, which is more complex than simply using hard-coded URLs/URL paths
You mean using Hypermedia As The Engine Of Application State is cumbersome and why people don't do "real rest"? Yes. I agree.
HATEOAS is neutral as to resource representation; you could have the invoices collection and all the individual resources within the (or one of the; resources don't need one and only one representation) owner resource representation.
If the collection or invoices can be accessed as individual resources (which, again, HATEOAS is neutral about), they should have their own URLs, but that doesn't prevent them from being incorporated in the parent resource representation.
Naive orthogonal CRUD on (the equivalent of) base tables of a normalized DB design is not a requirement of HATEOAS or REST, and it's often bad API whether or not you are aiming for REST. Its the a strawman every one beats on about REST, but it's got nothing to do with REST.
Well, yes, you need to know the semantics of the relationship, but not for parsing, because he content-type plus, where needed, internal data within the resource representation more specifically identifying the subtype should tell you what you need to know about handling the representation.
That's HATEOAS.
If you’re interacting with the api then it’s extremely likely you’re not going to write code that will automatically follow reference links and attempt to parse them dynamically.
You will need to know what fields are in the end point how they represent data (iso 8601 for dates? Unix timestamps?).
You’re substituting documentation with asking the api consumer to explore and discover and assume.
But you've documented how your API works anyway, right?
And let's not kid ourselves, much of our world runs on APIs that would really deserve the "bad design" handwave, end of the day that's often an aesthetic question.
However, you can have it both ways: in the customer response, use
"invoices": "/customer/7sn2J/invoices"
and have the server 307 redirect to "/invoices?customer=7sn2J", or whatever you prefer.> 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 honour all previously-issued URLs).
No more than it was previously.
> The URL passed out to the client by the server will have to include the primary key of the entity in a database plus some routing information, but because the client just echoes the URL back to the server and the client is never required to parse the URL, clients do not have to know the format of the URL.
Instead, you now have to require new kind of knowledge, one of the keys which must be present in schema and their meaning. E.g. knowing that "pets" key is present and leads to a relationship of a particular kind, with all the implicit logic added and documented. And what if you want to get pet's owners with some additional parameter, like only getting ones which are exclusively yours? Would you need to edit that "pets" url adding "&exclusively_owned=true"?
And of course since it is a type system, it now means you've got yet another type system to deal with in your universe. One with unknown and inconsistent semantics, and no natural support built in. Conceivably those semantics could be added and software built to support it, but rolling your own is going go yield a lot of effort with much less benefit.
It’s interesting how GraphQL changes the base point of the article concerning documentation/ease of api use.
In our GraphQL resolvers we typically add two fields, thing_id which resolves to the id string, and thing which resolves an object that you can drill into as desired.
I was starting to see a lot of GraphQL APIs only add “thing”, which meant you had to do a lot of queries like below just to get the id.
thing { id }Node Interface
The server must provide an interface called Node. That interface must include exactly one field, called id that returns a non‐null ID.
This id should be a globally unique identifier for this object, and given just this id, the server should be able to refetch the object.
https://facebook.github.io/relay/graphql/objectidentificatio...
So tonight we're going to regex like it's 1999.
https://tools.ietf.org/html/rfc8288
Additionally, compact URIs (CURIES) are also widely used in this context.
https://www.w3.org/TR/2010/NOTE-curie-20101216/
I feel that the author tried to reinvent HATEOAS but skipped a cursory bibliographical review and jumped right into reinventing the wheel, and one which has already been reinvented multiple times (HAL, JSON-LD, etc...)
This emperor has no clothes.
That's not the problem at all.
It would be the problem if the current state of the art was actually taken into account and discarded for some reason.
Instead, the state of the art (or even basic standard practices) is systematically ignored, and we end up seeing the same old wheel being supposedly invented again and again by people who fail to perform the flimsiest cursory bibliographical research on any given topic, and instead invest the bulk of their time announcing their poor reinvention of the wheel.
The web is based on linking. It's a very basic concept. Linking resources is not a new problem. What line of reasoning can possibly lead anyone to believe that this specific problem has never been researched by anyone before us, thus it's a sensible idea to simply dive head-first into coming up with a proposal that completely ignores any prior work?
Let's take RFC8288 as an example since you've brought it up. Where in that RFC does it discuss _why the fuck_ I would want to put an API link in the headers instead of the body?
The fact is that this RFC isn't "the standard". The standard thing is to put API links in the body with other attributes, and it's the standard because that's what everyone does, and because that's what makes sense. This RFC is a hammer for HTTP pedants to hit people over the head with.
The web is based on linking
And where to we expect those links to appear? In the header?
The article appears to start with a very similar assumption, and proposes use of URLs within resource representations instead of bare foreign-key IDs. I don't think the article can be accused of systematic ignorance of 'standard practices' or failing to perform "cursory bibliographical research"; stuff like HAL and JSON-LD are far from standard practice.
This series may benefit from a quick comparison of API design schools, comparing ways to express the a similar domain model in various styles, but it also seems to be trying not to get bogged down and dispense some prescriptive advice (instead of, say, overwhelm and despair).
> That's not the problem at all.
sorry, what is the real problem then, in your opinion?
i have never heard of that link in headers RFC until now. i have never heard of CURIEs but i remember seeing the xhtml example they gave. no one called them curies.
there is a huge communication gap, it seems, between what the standard defines and what people do in practice.
Who uses this "standard practice"? I haven't seen it. It seems rather awkward, even user-hostile, to put most of a resource's attributes in the body but put ones which happen to be links in the header.
I mean, think about it. The resource can (and will be) cached. Does it make any sense to also cache ephemeral links with it?
Then why are the single most important and widespread form of resource links, HTML URLs, always included in the response body i.e. in the HTML document itself?
Aside from that, I'm curious how do you manage alowing API clients to create new relationships or change them?
Google NIH syndrome
As another example of how the author failed to take into account basic standard practices, the author asserts that there is no standard for HTTP headers that specify API versions, but this baseless assertion requires ignoring the fact that media type versioning does exist and has been used for ages. The author even realizes that a solution based on the Accept header, which he prefers to invent a Accept-Version header, would fit his requirements. Ok, so why doesn't he just follow what has been standard for quite a few years and simply state the document version in the media type, which already is supported by any content-based routing scheme and is cached quite nicely?
JSONLD does define a standard way to indicate that a value is a link: @id (which can be specified in a/an @context) https://www.w3.org/TR/json-ld11/
One additional downside to storing URIs instead of bare references is that it's more complicated to validate a URI template than a simple regex like \d+ or [abcdef\=\d+]+
It may never make any difference on a small dataset, where storage was anyway unaware of differences between integer and text. But it would be hiding in the dark. And maybe in a few year a new recruit will have the outstanding idea to convert text-link to bigint to save some space...
It seems obvious that the cost-value for this is simply not there, if it was good enough, you'd see developers requesting it and many more vendors implementing it. So far I haven't seen any recent changes that might skew the cost-value towards the uri's favor, only the opposite (cue GraphQl).
Using uris have little benefits, but it does have the following problems:
As a user of the api:
* You need to keep an arbitrary length key in your database if you save references. It can cause some issues with certain setups (less so these days though).
* If you keep the entire URI as identity, then you can't use multiple endpoints. For instance lots of companies have an endpoint for production and one for reports - using URI for one endpoint in another is quite awkward.
* Working with queries is troublesome, especially with get request. Consider searching for all transaction of a specific account, where the account's identifier is `https://api.google.com/v1/account/123`
* Upgrading to a new version of the api (one with a different url like v1/v2) now not only requires you to change your code to work with the new version, but also migrate all previous ids you kept in your database, which is a much different and more error-prone issue then simply changing code.
From "A Practical Guide to Relational Database Design" from the year 2000. "Each relationship line should carry a pair of descriptive elements, which define the nature of the association between entities. A name is a single word or descriptive phrase; it should always contain a verb such as: owns, owned by, holds, administered by, etc. Examples from our simple model are: A PART is sold on an ORDER LINE. An ORDER LINE is placed for a PART."
But, this has been lost because the practicality is that it is hard to know what is the element. As other comments points.
Probably the best is both worlds: PersonId_Owner. PersonId_Veterinary. Or something similar.
It seems that such a discussion should have been solved decades ago. And here we are. :)
Ahh I was correct:
> I have never used GraphQL, so I can't endorse it, but you may want to evaluate it as an alternative to designing and implementing your own API query capability.
You really shouldn't write this giant article without having tried that.
https://en.wikipedia.org/wiki/HATEOAS
The idea has been around for a while; I personally don't think it is a good idea.
There is even a content type (or two) for it: application/hal+json and application/hal+xml.
Instead, the relationship between the response document and the URL's target is implicit, probably guessed from the naming of the key or maybe noted in the response document's definition.
The point of HATEOAS is that a client who understands the meaning of certain link relations (aka "rels"), such as ones in the IANA registry [1], can interact with these referred-to resources using the Standard Interface (of GET, POST, PUT, etc).
Only in the section where the article talks about ways to express links in JSON do link relations appear.
[1] https://www.iana.org/assignments/link-relations/link-relatio...
> [...]
> There is even a content type (or two) for it: application/hal+json and application/hal+xml.
Also, the original content-type for REST, including HATEOAS, text/html.
On one level we got ID unique identifier of a resource, on another level we have URL, how to get a specific resources.
They are just different things that shouldn't be mixed.
What if tomorrow I want to get the same resource via graphql? Or in a message bus?
While this looks good on paper, in practice URLs were relatively stable in the early days of the internet and so they turned into de facto names before lots of effort was put into making URNs work. Now, we’re struggling with the issues they originally foresaw, but weren’t able to follow through with a working implementation.
(For more details, see https://danielmiessler.com/study/url-uri/ where I got much of this information)
If the ID is also a link, it is guaranteed to be globally unique (like a Relay Node ID in GraphQL).
If you want to get the same resource via GraphQL, just use the same URL-ID. In fact, the author mentioned the possibility of base64-ing the link to prevent clients from relying on its structure, which is also a common pattern with IDs in GraphQL.
The ID is the maximum cardinality of an entity (informally the smallest set of values of such entity necessary to uniquely identify it), the link is how to find the entity.
What happen if you want to deprecated your API?
There are other way to share the link of a resource,like use headers.
Then again, from a strictly practical point of view in 99.9% of the case it won't change anything, but:
1. Eventually there will be cases where it does matter, and then it will be an huge mess.
2. Why shut yourself a door only to don't read an header and obtain exactly the same information?
For human it's obvious that dog has an owner, so field "owner" should be used, but for code - you need to write it, "document it". So if you're going to "document" every field containing link to external resource, you'll end up with even more code, than just "documenting" API endpoints.
Also, pretty often you need multiple IDs of entities to send POST/PUT request - just to create a relation.
POST /adoption, owner_id=5, dog_id=7.
How should it look with links? Will it be issue for the server to parse them? And it's just simple case with 1 to 1 relation, sometimes you need to add sets of objects to another entity.
It's a really bad advice and after reading this I'm not sure I should trust other articles from that source.
> How should it look with links?
Like this:
POST /adoption, owner=/people/5, dog=/pets/7
> Will it be issue for the server to parse them?
Why would it be?
There is no single reason for this complication. The ONLY motivation author had - less knowledge about API endpoints on the client. But simultaneously it means more knowledge about the fields where links are stored, so it doesn't save nothing.
Feel free to ignore me.
[0] https://www.quora.com/Is-the-sentence-dont-do-nothing-correc...
If you use links for read, you should also use them for writes, otherwise it's quite inconsistent. So now you need to add a lot of parsing everywhere to extract the id's out of the urls, just for the sake of being more dogmatic
If in your example your usergroup and user are managed by the same service, then usually you should already have a feature in your framework that parses `/user/123` into its individual component and finds the relevant entity.
Ideally you would use that.
What's the point? None of this is useful to me, all of this is extra complexity. Why would I want to expose every addressable entity through URLs and HTTP? That's not what IDs are for.
I'm aware that this fits into the whole REST idea. I still don't care.
"In this specification, a link is a typed connection between two resources and is comprised of:
o a link context,
o a link relation type (Section 2.1),
o a link target, and
o optionally, target attributes (Section 2.2).
A link can be viewed as a statement of the form "link context has a
link relation type resource at link target, which has target
attributes".
For example, "https://www.example.com/" has a "canonical" resource at
"https://example.com", which has a "type" of "text/html".
"That's why you need a standardized link component that is globally accepted/understood that takes into account all parts of the linking, instead of having various ways depending on the API/JSON-based Media Type to communicate that something is a link.
May be it makes sense when you're writing an API and some different person writes a client and she's so shy that she don't want to even ask you. Yeah, she can inspect answer and find out that this seems like a link to query further. I never was in that situation, I was always building all software myself, so for me this does not make sense.
I do like the idea from Stripe of having Accept header versioning, but pinning every new client to default to the newest GA version. Gets around most of the DX concerns I raised, but it's a bit more machinery to wire up.
/pets?owner=/people/98765
or
/pets?owner=/org/98765
which makes your api more polymorphic.Having said that I don't think URL is the right term to describe this. It's more like a <type, id> tuple.
Essentially, a foreign key is viewed as a relational workaround for representing links with some significant drawbacks and the question is why not to use links directly without relational wrapping.
[1] Joins vs. Links or Relational Join Considered Harmful: https://www.researchgate.net/publication/301764816_Joins_vs_...
> Yet, classical references miss some properties which are of crucial importance for data modeling. How links can be revisited in order to overcome these drawbacks will be our focus for future research.
These architectures aren't equivalent alternatives. Pick the right tools for the job, and use the right tool appriately.
I absolutely agree. GraphQL clearly addresses a pain point, or a gap. I just don't think it should be seen as a replacement. Pick the right tool for the job.
From that point on I try to use it as much as possible. A typical API response for my projects looks like this:
{
"id": "3ccf0f1b-dd3f-48d9-911a-ddf479078c37",
"name": "Quantus Tasks",
"description": "Quantus Tasks Desktop Application",
"license_key_type": "alphanumeric_32",
"created_at": "2019-05-12T10:45:42.089406Z",
"updated_at": "2019-05-12T10:45:42.089406Z",
"_links": {
"self": {
"href": "http://localhost:8000/v1/applications/3ccf0f1b-dd3f-48d9-911a-ddf479078c37"
},
"licenses": {
"href": "http://localhost:8000/v1/applications/3ccf0f1b-dd3f-48d9-911a-ddf479078c37/licenses"
},
"templates": {
"href": "http://localhost:8000/v1/applications/3ccf0f1b-dd3f-48d9-911a-ddf479078c37/templates"
},
"apikeys": {
"href": "http://localhost:8000/v1/applications/3ccf0f1b-dd3f-48d9-911a-ddf479078c37/apikeys"
}
}
}
It still has the ID field in there for cases where the client needs to store the id itself but it should not be used to template URI's for related resources, the links are there for that.Hal clients for this use case do exist. you point them to an entrypoint and they can discover and generate the necessary code/methods for interacting with the API.
For example: https://github.com/pezra/hal-client
I don't get the intent at all here, but I have a suspicion whatever problem this tries to solve is better solved by UUIDs or by doing nothing out of the ordinary.
One benefit of using urls as ids is that it no longer is just an id, it also describes where you can get it's representation.
Also RDF endpoints usually use resolvable URI's to connect concepts and objects with each other.