I have started an on-line book of recipes for building hypermedia APIs with the Mason (hyper)media type. It is very much work in progress but hopefully I can add one or two recipes a week on my daily train commute to and from work.
The book source is hosted on GitHub and is made available on-line at GitBook in various formats. Later on I may host it another server depending on how GitBook turns out to work with - but so far it has been a nice experience.
You are most welcome to add issues, fork it and send me pull requests for improvements.
onsdag, juli 01, 2015
Introducing the Mason Cook Book
tirsdag, juni 16, 2015
Mason Draft 2 ready for use
I am happy to announce that Mason (the JSON + hypermedia format) is now ready for use in Draft 2. See https://github.com/JornWildt/Mason/blob/master/Documentation/Mason-draft-2.md.
For those that haven't heard about Mason before - please take a look at https://github.com/JornWildt/Mason. Mason is a JSON based format with conventions for representing API data and hypermedia control elements.
This version combines links, actions and link templates into one single @controls object. As the name indicates this object contains all the hypermedia elements that control the application.
This move to @controls makes it possible to combine link templates with POST data - and should make it easier to parse and represent hypermedia elements in code.
There are currently no further ideas in the pipeline that could change how things are represented in Mason. Future versions may though add new features.
Feedback is as always appreciated :-)
For those that haven't heard about Mason before - please take a look at https://github.com/JornWildt/Mason. Mason is a JSON based format with conventions for representing API data and hypermedia control elements.
This version combines links, actions and link templates into one single @controls object. As the name indicates this object contains all the hypermedia elements that control the application.
This move to @controls makes it possible to combine link templates with POST data - and should make it easier to parse and represent hypermedia elements in code.
There are currently no further ideas in the pipeline that could change how things are represented in Mason. Future versions may though add new features.
Feedback is as always appreciated :-)
fredag, december 19, 2014
Announcing Macaroons.Net - a C# implementation of macaroons authorization credentials
In my previous blog post I introduced "macaroons" - a new technique for creating authorization credentials.
But I even went a bit further and created a C# implementation of macaroons called Macaroons.Net. You can find it on GitHub at https://github.com/JornWildt/Macaroons.Net together with examples and documentation.
Have fun.
But I even went a bit further and created a C# implementation of macaroons called Macaroons.Net. You can find it on GitHub at https://github.com/JornWildt/Macaroons.Net together with examples and documentation.
Have fun.
Macaroons authorization credentials, better than cookies
This was the year I first heard of the term "macaroon" used in the context of the web, authorization frameworks and other crypto stuff. I had absolutely no idea of what it was, but "the web" said it was good, so I got curious and did some studying. It turned out to be a technique for creating authorization tokens with some very interesting properties:
Here is a small scenario illustrating the above features:
The technology for this flow is not yet perfect as there are some interoperability problems regarding how to encode third party requirements like "being authorized as Cecilia @ Twitter". But the underlying crypto stuff is solid and published in the paper "Macaroons: Cookies with Contextual Caveats for Decentralized Authorization in the Cloud" by Arnar Birgisson, Joe Gibbs Politz, Úlfar Erlingsson, Ankur Taly, Michael Vrable and Mark Lentczner.
Personally I think this little piece of technology has a great potential for creating distributed system.
- Proof carrying: a macaroon carries its own proof of authorization, cryptographically secured.
- Delegation: a macaroon can be given to another user who can then act on your behalf.
- Attenuation: any user can further restrict (attenuate) the authorization before sharing the macaroon with others.
- Distributed authorization: any user can require authorization by other services before using a macaroon.
Here is a small scenario illustrating the above features:
- Alice wants to share a set of images on a photo sharing website. Lets call it "Phlocker" for now.
- Alice asks Phlocker to create a macaroon which enables access to exactly those images.
- Alice sends the macaroon to Bob.
- Bob receives the macaroon, most likely as part of a URL to Phlocker, and he uses it to access the images.
- Bob decides to share exactly one of the images with Cecilia. So Bob creates a new macaroon from the original macaroon without involving Phlocker at all. This new macaroon "attenuates" the original macaroon and restricts it to the single image.
- Bob does not want Cecilia to share the image with others, so he attenuates the macaroon even further by adding the requirement that only Cecilia, as identified by her Twitter account, should be allowed to use the macaroon.
- Bob sends the macaroon to Cecilia.
- Cecilia receives the macaroon and sees the requirement of being logged into Twitter as Cecilia.
- Cecilia interacts with Twitter to prove her identity and Twitter issues a discharge macaroon to Cecilia. This is all done without Twitter knowing why Cecilia needs the authorization.
- Cecilia prepares the discharge macaroon for use at Phlocker and sends it together with the original macaroon she received from Bob.
- Phlocker checks Cecilia's macaroon from Bob, recognizes the Twitter identity requirement and verifies it with the discharge macaroon.
- Cecilia gets to see the single image without being able to see the other images that Alice originally authorized Bob to access.
The technology for this flow is not yet perfect as there are some interoperability problems regarding how to encode third party requirements like "being authorized as Cecilia @ Twitter". But the underlying crypto stuff is solid and published in the paper "Macaroons: Cookies with Contextual Caveats for Decentralized Authorization in the Cloud" by Arnar Birgisson, Joe Gibbs Politz, Úlfar Erlingsson, Ankur Taly, Michael Vrable and Mark Lentczner.
Personally I think this little piece of technology has a great potential for creating distributed system.
lørdag, august 02, 2014
Take away from the 2014 API-Craft conference in Detroit
Last week I attended the 2014 API-Craft conference in Detroit - and I had a great time! Met lots of interesting people, had great conversations and learned a lot about what other people make out there.
Some of the stuff I saw and listen to in Detroit made a few pieces of puzzle click together in my brain. First there was Z who reminded me that we still don't have any good description language for documenting resource oriented hypermedia APIs. I've heard that before and been wondering how it would look like.
Then I talked with Sergey and Dmitri who showed me the resource diagram for their API - this one reminded me so much of UML diagrams that I think we should look into that for inspiration.
I was also at the "Documenting APIs" session where I suddenly found myself talking about our own API documentation - which is written in Word (and that's okay, kind'a). It made me realize that, at its core, such a documentation consists of resource descriptions, link relation descriptions, action descriptions and of course some kind of overview, introduction and tutorial sections.
Someone asked us to explain what a hypermedia API is in one sentence. I came up with "That is an API which can be documented without writing one single absolute URL or relative URL path". I don't exactly think that will catch on, especially not outside this community, but I do believe it is true - if you need to explain URL structures then you are missing something. Unfortunately that one sentence doesn't tell you how to actually implement such an API and as such it is really not very useful.
[I'm pretty sure there is a good Yoda quote to put in here ... like, you now ... "The links with you very strong are here, Luke". Anyone got a better one?]
Dave introduced me to his JSON based description language for APIs and it made me realize that you can do awesome things even in a dead simple format like JSON. Why having to state <twice>everything</twice> when you can do { "single": "everything" }.
Then there were people talking about resources and state machines (thanks again Z). Personally I don't believe much in that analogy - it kind of confuses the graph of resource relationships with the graph of a way-too-simple-never-to-be-found-in-real-life state machine. Z did try to convince me about this but never succeeded - maybe because I am highly colored by my PhD thesis on automatic verification of obnoxiously great state machines :-)
We also got a great deal around API explorers/browsers of various kinds. It seems like every media type have such one now a days - and it makes great sense to me. I truly believe in the power it has when it comes to learning a new API. Thanks to Kristopher Kleva for his story about links, actions and the Sirene browser (you really should blog about that experience!).
I also met Pete Gamache who is the guy behind HyperResource - unfortunately we never really spoke together. He's hypermedia client for Ruby is an interesting solution for interacting with hypermedia APIs in code. Its not exactly new as the same kind of ideas exists in the older tool Restfulie (for Ruby) and my own Ramone library (for C#) - but none the less it shows that there are something worth pursuing here.
All the talks about tooling, SDKs and object models for API resources made me want to work a bit on Ramone and Mason again. It could be cool to make a C# hypermedia resource representation that would allow the client developer to follow links and execute actions in an easy and intuitive way - while at the same time be able to hide some of the stuff that complicates client code in order to make it long lasting and handle (some types of) API changes.
So, thanks to all of you - also those of you that I have forgotten to mention here and of course the people at Apigee that made all of this possible!
Some of the stuff I saw and listen to in Detroit made a few pieces of puzzle click together in my brain. First there was Z who reminded me that we still don't have any good description language for documenting resource oriented hypermedia APIs. I've heard that before and been wondering how it would look like.
Then I talked with Sergey and Dmitri who showed me the resource diagram for their API - this one reminded me so much of UML diagrams that I think we should look into that for inspiration.
I was also at the "Documenting APIs" session where I suddenly found myself talking about our own API documentation - which is written in Word (and that's okay, kind'a). It made me realize that, at its core, such a documentation consists of resource descriptions, link relation descriptions, action descriptions and of course some kind of overview, introduction and tutorial sections.
Someone asked us to explain what a hypermedia API is in one sentence. I came up with "That is an API which can be documented without writing one single absolute URL or relative URL path". I don't exactly think that will catch on, especially not outside this community, but I do believe it is true - if you need to explain URL structures then you are missing something. Unfortunately that one sentence doesn't tell you how to actually implement such an API and as such it is really not very useful.
[I'm pretty sure there is a good Yoda quote to put in here ... like, you now ... "The links with you very strong are here, Luke". Anyone got a better one?]
Dave introduced me to his JSON based description language for APIs and it made me realize that you can do awesome things even in a dead simple format like JSON. Why having to state <twice>everything</twice> when you can do { "single": "everything" }.
Then there were people talking about resources and state machines (thanks again Z). Personally I don't believe much in that analogy - it kind of confuses the graph of resource relationships with the graph of a way-too-simple-never-to-be-found-in-real-life state machine. Z did try to convince me about this but never succeeded - maybe because I am highly colored by my PhD thesis on automatic verification of obnoxiously great state machines :-)
We also got a great deal around API explorers/browsers of various kinds. It seems like every media type have such one now a days - and it makes great sense to me. I truly believe in the power it has when it comes to learning a new API. Thanks to Kristopher Kleva for his story about links, actions and the Sirene browser (you really should blog about that experience!).
I also met Pete Gamache who is the guy behind HyperResource - unfortunately we never really spoke together. He's hypermedia client for Ruby is an interesting solution for interacting with hypermedia APIs in code. Its not exactly new as the same kind of ideas exists in the older tool Restfulie (for Ruby) and my own Ramone library (for C#) - but none the less it shows that there are something worth pursuing here.
All the talks about tooling, SDKs and object models for API resources made me want to work a bit on Ramone and Mason again. It could be cool to make a C# hypermedia resource representation that would allow the client developer to follow links and execute actions in an easy and intuitive way - while at the same time be able to hide some of the stuff that complicates client code in order to make it long lasting and handle (some types of) API changes.
So, thanks to all of you - also those of you that I have forgotten to mention here and of course the people at Apigee that made all of this possible!
torsdag, marts 27, 2014
Modelling a Shipment example as a hypermedia service with Mason
Yesterday I was attending the "RAML" workshop at the API Strategy konference. In this workshop the speakers introduced a very simple little Web API; It allowed a customer to GET a (shipment) quote and afterwards create (POST) an actual shipment request based on the quote.
I decided that it could be fun to hypermedia-ize the example and show how it could be represented using the media type Mason. So here we go :-)
The first step is to ask for a quote; the customer has a package of some sort and needs to ship it from A to B, so he access the shipment service and asks for a quote (a price) given the size, weight, origin and destination for the package.
In the original example you could ask for a quote by issuing a GET request to /quote. But I believe that asking for a quote would result in a concrete quote being created and stored in the system as a separate resource to access later on, either by the customer or by the customer service of the shipment company. So I would rather go for a POST of a quote request followed by a redirect to the newly created quote.
At this point we could either document how to POST such a quote - or we could tell the client how to do it using hypermedia controls - and obviously I would go for the later. So lets ask the service for instructions and issue a GET /quote request. The output is a Mason document with suitable hypermedia controls embedded in it:
{
"@namespaces":
{
"myth":
{
"name": "http://mythological-shipment.com/api/rel-types"
}
},
"@actions":
{
"myth:quote":
{
"type": "json",
"method": "POST",
"href": "http://mythological-shipment.com/api/quote",
"title": "Ask for a quote",
"description": "Ask for a quote by posting package details. Weight is in kilograms, volume in cubic decimeters, origin and destination must be known identifiers for airports.",
"schemaUrl": "... URL to JSON schema describing the request ..."
}
}
}
The client reads this action specification, encodes the package details in JSON and POST it to the URL of the "href" property. As a result the service creates a new quote resource and redirects the client to it:
Request:
POST http://mythological-shipment.com/api/quote HTTP/1.1
content-type: application/json
{
"weight": 2.3,
"volume": 4,
"origin": "CPH",
"destination": "AMS"
}
Response:
201 Created
Location: http://mythological-shipment.com/api/quotes/myqo-129-gyh
Now the client can GET the newly created quote to get further instructions of how to accept the quote. The result is again a Mason representation of the quote itself plus hypermedia controls for accepting the quote:
{
"id": "myqo-129-gyh",
"weight": 2.3,
"volume: 4,
"origin": "CPH",
"destination": "AMS":
"price": 12,
"@links":
{
"self":
{
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh"
}
},
"@actions":
{
"myth:accept-quote":
{
"type": "POST",
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh/state",
"template":
{
"accepted": "yes"
}
}
}
}
As you can see the quote has a "self" link identifying the location of the quote resource. It also have a "accept-quote" action that instructs the client about how to accept the quote. In this case all the client has to do is to POST a predefined JSON value to http://mythological-shipment.com/api/quotes/myqo-129-gyh/state.
The result of accepting a quote is that it is converted to a sales order (in lack of better domain understanding - there's probably a better word for it). So the accept-quote operation results in a redirect to the newly create sales order which the client can GET:
{
"id": "myqo-129-gyh",
"weight": 2.3,
"volume: 4,
"origin": "CPH",
"destination": "AMS":
"price": 12,
"@links":
{
"self":
{
"href": "http://mythological-shipment.com/api/orders/myqo-129-gyh"
},
"myth:quote":
{
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh"
},
"myth:shipment-label":
{
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh/label",
"type": "application/pdf"
}
}
}
At last the customer needs a shipment label to print out and stick onto the package. All it has to do is to follow the "myth:shipment-label" link and GET the PDF. Thats it.
/Jørn
I decided that it could be fun to hypermedia-ize the example and show how it could be represented using the media type Mason. So here we go :-)
The first step is to ask for a quote; the customer has a package of some sort and needs to ship it from A to B, so he access the shipment service and asks for a quote (a price) given the size, weight, origin and destination for the package.
In the original example you could ask for a quote by issuing a GET request to /quote. But I believe that asking for a quote would result in a concrete quote being created and stored in the system as a separate resource to access later on, either by the customer or by the customer service of the shipment company. So I would rather go for a POST of a quote request followed by a redirect to the newly created quote.
At this point we could either document how to POST such a quote - or we could tell the client how to do it using hypermedia controls - and obviously I would go for the later. So lets ask the service for instructions and issue a GET /quote request. The output is a Mason document with suitable hypermedia controls embedded in it:
{
"@namespaces":
{
"myth":
{
"name": "http://mythological-shipment.com/api/rel-types"
}
},
"@actions":
{
"myth:quote":
{
"type": "json",
"method": "POST",
"href": "http://mythological-shipment.com/api/quote",
"title": "Ask for a quote",
"description": "Ask for a quote by posting package details. Weight is in kilograms, volume in cubic decimeters, origin and destination must be known identifiers for airports.",
"schemaUrl": "... URL to JSON schema describing the request ..."
}
}
}
The client reads this action specification, encodes the package details in JSON and POST it to the URL of the "href" property. As a result the service creates a new quote resource and redirects the client to it:
Request:
POST http://mythological-shipment.com/api/quote HTTP/1.1
content-type: application/json
{
"weight": 2.3,
"volume": 4,
"origin": "CPH",
"destination": "AMS"
}
Response:
201 Created
Location: http://mythological-shipment.com/api/quotes/myqo-129-gyh
Now the client can GET the newly created quote to get further instructions of how to accept the quote. The result is again a Mason representation of the quote itself plus hypermedia controls for accepting the quote:
{
"id": "myqo-129-gyh",
"weight": 2.3,
"volume: 4,
"origin": "CPH",
"destination": "AMS":
"price": 12,
"@links":
{
"self":
{
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh"
}
},
"@actions":
{
"myth:accept-quote":
{
"type": "POST",
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh/state",
"template":
{
"accepted": "yes"
}
}
}
}
As you can see the quote has a "self" link identifying the location of the quote resource. It also have a "accept-quote" action that instructs the client about how to accept the quote. In this case all the client has to do is to POST a predefined JSON value to http://mythological-shipment.com/api/quotes/myqo-129-gyh/state.
The result of accepting a quote is that it is converted to a sales order (in lack of better domain understanding - there's probably a better word for it). So the accept-quote operation results in a redirect to the newly create sales order which the client can GET:
{
"id": "myqo-129-gyh",
"weight": 2.3,
"volume: 4,
"origin": "CPH",
"destination": "AMS":
"price": 12,
"@links":
{
"self":
{
"href": "http://mythological-shipment.com/api/orders/myqo-129-gyh"
},
"myth:quote":
{
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh"
},
"myth:shipment-label":
{
"href": "http://mythological-shipment.com/api/quotes/myqo-129-gyh/label",
"type": "application/pdf"
}
}
}
At last the customer needs a shipment label to print out and stick onto the package. All it has to do is to follow the "myth:shipment-label" link and GET the PDF. Thats it.
/Jørn
onsdag, februar 26, 2014
API authentication considerations and best practices
I have been answering a few security questions on Stackoverflow and going through some APIs on programmableweb.com - and it keeps amazing me how often people gets HTTP authorization wrong.
The typical questions I have noticed on SO are something like "I want to secure my API, have control of clients and require users to login - but I don't want to use OAuth". Duh? Why not? Perhaps because OAuth is conceived as being too difficult to work with? Well, OAuth2 is definitively not difficult (OAuth1 is another story though).
But lets take a look at some of the existing practices:
API keys in URLs: one example is the Finish National Gallery API (which I somehow stumbled upon). Here you are required to obtain an API key and put it into the URL in every request made to the API:
http://kokoelmat.fng.fi/api/v2?apikey=********&q=A+III+2172
API keys in custom headers: one example is from DocuSign. They require you to encode both your (developer) user name, password and API key in a JSON object and then send that in a custom header X-DocuSign-Authentication:
GET /some-url
X-DocuSign-Authentication: { "Username": "...", "Password": "...", "IntegratorKey": "..." }
... more ...
Signed URL/body parameters: one example is last.fm which requires you to use your API key to obtain a session token and use that token later on to sign requests, either using URL parameters or in the body of the HTTP request.
HTTP Basic authentication: GitHub supports authentication via the standard HTTP basic authentication mechanism where you supply username and password BASE64 encoded in the "Authorization" header.
OAuth1 and Oauth2: PhotoBucket uses OAuth1 and BaseCamp uses Oauth2 (in addition to HTTP basic authentication).
I did set out with the expectation of finding many more strange authorization schemes, but it turned out that at least most of the big players use OAuth1 or OAuth2. That's great! Now we just need to get the word out to all the "dark matter developers" out there (as Scott Hanselman calls them).
1) API keys in URLs are very easily accidentally exposed to third parties. If you take a copy of the URL and mail it to somebody you will end up sending your private key to someone else. For the same reason API keys may end up in log files here and there. Not good!
2) API keys in URLs changes your resource URL such that it depends on who is using it. Instead of everybody referring to /some-items/1234 it will be /some-items/1234?key=abc for one user and /some-items/1234?key=qwe for another - and these two are completely different URLs even though they "only" differ on the query parameters. It is semantically the same as encoding the key in the path segment as for instance /api/abc/some-items/1234 and /api/qwe/some-items/1234 which I don't expect any one to think of as a good idea - right?
3) API keys in headers are better than API keys in URLs since it will keep the URL stable for all users and it doesn't expose API keys when sending links to others. The problem though is that you are still sending your secret credentials (the API key) over the wire and it may be wiretapped by third parties. Another problem is that a client may accidentally connect to the wrong server (by misconfiguration or otherwise) and expose its credentials there.
4) Signed requests (done right!) should be preferred over sending the API key directly. The signature should not be part of the URL for the reasons stated above - and the same goes somehow for sending the signature in the body since different users will see different bodies which is not necessary when you have a standard HTTP header for the purpose.
5) Proprietary methods for signing requests are prone to design errors as it is easy to get the signature mechanism wrong - and thus accidentally making the signature technique easy to circumvent.
6) Proprietary methods for signing requests requires client developer to understand yet another signature mechanism. It also makes it less likely to find existing client libraries to handle the crypto stuff. Both of these issues makes client adoption of your API less likely. And you know what, dear server developer? Your client developers will call for support and it will end up on YOUR table, reducing your ability to focus on coding the next great thing! So stick to well documented standards - it will be less annoying for everybody including yourself.
7) HTTP basic authentication is great for debugging and getting started scenarios but should not be used in production. The problem is that client credentials are send in clear text and are thus susceptible to accidental exposure as mentioned before. Your API should support basic authentication as it will make it possible to explore the API using a standard web browser - but it should be disabled in production.
8) It should be possible to revoke API keys in case they are compromised in some way.
What kind of technique would solve all of these issues? Well, Oauth2 is one standard solution; it uses the HTTP "Authorization" header (thus avoiding authentication stuff in URL and body), it is a standard and used correctly it protects clients from exposing their API keys to the server and over the wire.
Another solution is to use SSL/TLS with client certificates. With the proper HTTP client libraries this can be as easy as loading a certificate (one line of code) and assigning it to the HTTP request object (second line of code). This can although not authorize a combination of both client credentials and end user credentials.
Before jumping into OAuth2 I better explain some of the terms used when talking about OAuth2 (mostly copied from the RFC at http://tools.ietf.org/html/rfc6749#section-1.1):
- Protected resources: the data you want to protect.
- Resource owner: An entity capable of granting access to a protected resource. The "entity" is often a person - the end user.
- Resource server: The server hosting the protected resources.
- Client: An application making protected resource requests on behalf of the resource owner. This can for instance be a mobile application, a website or a background integration process impersonating an existing end user.
- Client credentials: a pair of client ID and client secret. This could be your developer or application ID and API key.
- Resource owner password credentials: the typical user-name/password combination issued to an end user.
OAuth2 has four different modes of operating (called flows) - going from the relatively complex 3-legged authorization flow to the very simple "client credentials" authorization flow. At least one of the flows should fit into just about any public API ecosystem out there - and if not then it is possible to add new extension flows (as for instance Google does with the JWS implementation).
At its core OAuth2 has only two high level steps:
1) Swap a set of user and/or client credentials for an access token (authorization step), and
2) Use the access token to access the API resources.
That's it. It can be very simple. The difficult part of OAuth2 is the many ways a client can obtain an access token.
Here I will focus on a scenario with a trusted client that accepts user credentials and acts on behalf of them. This can be very useful for many internal integration patterns where no humans are involved. I won't cover the scenario where an untrusted client (third party website) needs to access the end user's resources using the 3-legged authorization flow.
At a suitable high level OAuth2 only has two steps as mentioned before: 1) authorization, 2) resource access. The output of a successful authorization step is always an access token which must be used in subsequent requests to the resource server (the API).
In most cases the access token is a so called "bearer token" - a token which the bearer can present to gain access to resources. Such a token has no built-in semantics and should be considered as nothing but a plain text string.
The bearer token is included in the HTTP Authorization header like this:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer SOME-TOKEN
This is just about the simplest flow possible (see http://tools.ietf.org/html/rfc6749#section-4.4): all the client has to do is to send it's client credentials (ID and secret) as if it was using HTTP basic authorization. In return the client receives an access token it can use in subsequent requests for the protected resources. Here is an example from the RFC:
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
The response could be:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer"
}
This flow allows the client to act on behalf of itself but it does not include any end user information.
If a client needs to act on behalf of the end user (the resource owner) then it can use the "Resource Owner Password Credentials Grant". This flow is almost as simple is the previous flow - all the client has to do is to add the client credentials to the authorization request. Here is an example from the RFC:
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w
The response could be:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer"
}
This flow allows the client to act on behalf of the end user. The client application must be trusted as the end user will have to pass his/her credentials to it.
There is one big problem with the two simple flows mentioned above; both of them pass the client and end user credentials in clear text. For this reason OAuth2 makes it mandatory to use TLS/SSL to encrypt all of the requests. Neither does these flows cover scenarios with untrusted clients (such as a third party website that wants to access an end users resources on a different server) - but that scenario is covered in the "Authorization Code Grant" scenario which I will not discuss here.
The use of TLS/SSL protects the credentials from eavesdropping and man-in-the-middle attacks but it does not protect against sending credentials to the wrong server - either by misconfiguration or because the server has been compromised.
This lack of protection is perhaps one of the biggest difference between OAuth1 and OAuth2; OAuth1 protects credentials by signing requests instead of sending the raw credentials. This requires a rather complex signing algorithm which has caused many headaches over the time. OAuth2 trades the protection of credentials for simplicity which makes it a lot easier to use - but susceptible to leaking credentials to rogue servers.
It is possible to protect credentials from this problem though but it requires clients to use some complex crypto stuff to sign requests instead of sending the raw credentials (just like OAuth1 does). This is what Google does when it requires requests to be signed using JSON Web Signatures (JWS).
If you are using .NET then my Ramone HTTP library has support for OAuth2 with JWS as can be seen in this example: http://soabits.blogspot.com/2013/03/using-ramone-for-oauth2-authorization.html.
One more word of caution - websites, mobile apps, desktop apps and similar with public clients cannot protect their client credentials. Other application may be able to do it (server to server integrations for instance) but public clients, be it JavaScript, byte code or assembler, can always be downloaded, decompiled and scrutinized by various forensic tools and in the end it will be impossible to keep client secrets from being stolen. This is a fact we have to live with.
Client credentials can be useful for statistics. They also give the ability to revoke credentials in order to block rogue applications - but they cannot be trusted in general.
The typical questions I have noticed on SO are something like "I want to secure my API, have control of clients and require users to login - but I don't want to use OAuth". Duh? Why not? Perhaps because OAuth is conceived as being too difficult to work with? Well, OAuth2 is definitively not difficult (OAuth1 is another story though).
But lets take a look at some of the existing practices:
API keys in URLs: one example is the Finish National Gallery API (which I somehow stumbled upon). Here you are required to obtain an API key and put it into the URL in every request made to the API:
http://kokoelmat.fng.fi/api/v2?apikey=********&q=A+III+2172
API keys in custom headers: one example is from DocuSign. They require you to encode both your (developer) user name, password and API key in a JSON object and then send that in a custom header X-DocuSign-Authentication:
GET /some-url
X-DocuSign-Authentication: { "Username": "...", "Password": "...", "IntegratorKey": "..." }
... more ...
Signed URL/body parameters: one example is last.fm which requires you to use your API key to obtain a session token and use that token later on to sign requests, either using URL parameters or in the body of the HTTP request.
HTTP Basic authentication: GitHub supports authentication via the standard HTTP basic authentication mechanism where you supply username and password BASE64 encoded in the "Authorization" header.
OAuth1 and Oauth2: PhotoBucket uses OAuth1 and BaseCamp uses Oauth2 (in addition to HTTP basic authentication).
I did set out with the expectation of finding many more strange authorization schemes, but it turned out that at least most of the big players use OAuth1 or OAuth2. That's great! Now we just need to get the word out to all the "dark matter developers" out there (as Scott Hanselman calls them).
Things to be aware of
1) API keys in URLs are very easily accidentally exposed to third parties. If you take a copy of the URL and mail it to somebody you will end up sending your private key to someone else. For the same reason API keys may end up in log files here and there. Not good!
2) API keys in URLs changes your resource URL such that it depends on who is using it. Instead of everybody referring to /some-items/1234 it will be /some-items/1234?key=abc for one user and /some-items/1234?key=qwe for another - and these two are completely different URLs even though they "only" differ on the query parameters. It is semantically the same as encoding the key in the path segment as for instance /api/abc/some-items/1234 and /api/qwe/some-items/1234 which I don't expect any one to think of as a good idea - right?
3) API keys in headers are better than API keys in URLs since it will keep the URL stable for all users and it doesn't expose API keys when sending links to others. The problem though is that you are still sending your secret credentials (the API key) over the wire and it may be wiretapped by third parties. Another problem is that a client may accidentally connect to the wrong server (by misconfiguration or otherwise) and expose its credentials there.
4) Signed requests (done right!) should be preferred over sending the API key directly. The signature should not be part of the URL for the reasons stated above - and the same goes somehow for sending the signature in the body since different users will see different bodies which is not necessary when you have a standard HTTP header for the purpose.
5) Proprietary methods for signing requests are prone to design errors as it is easy to get the signature mechanism wrong - and thus accidentally making the signature technique easy to circumvent.
6) Proprietary methods for signing requests requires client developer to understand yet another signature mechanism. It also makes it less likely to find existing client libraries to handle the crypto stuff. Both of these issues makes client adoption of your API less likely. And you know what, dear server developer? Your client developers will call for support and it will end up on YOUR table, reducing your ability to focus on coding the next great thing! So stick to well documented standards - it will be less annoying for everybody including yourself.
7) HTTP basic authentication is great for debugging and getting started scenarios but should not be used in production. The problem is that client credentials are send in clear text and are thus susceptible to accidental exposure as mentioned before. Your API should support basic authentication as it will make it possible to explore the API using a standard web browser - but it should be disabled in production.
8) It should be possible to revoke API keys in case they are compromised in some way.
What kind of technique would solve all of these issues? Well, Oauth2 is one standard solution; it uses the HTTP "Authorization" header (thus avoiding authentication stuff in URL and body), it is a standard and used correctly it protects clients from exposing their API keys to the server and over the wire.
Another solution is to use SSL/TLS with client certificates. With the proper HTTP client libraries this can be as easy as loading a certificate (one line of code) and assigning it to the HTTP request object (second line of code). This can although not authorize a combination of both client credentials and end user credentials.
OAuth2
OAuth2 roles and terms
Before jumping into OAuth2 I better explain some of the terms used when talking about OAuth2 (mostly copied from the RFC at http://tools.ietf.org/html/rfc6749#section-1.1):
- Protected resources: the data you want to protect.
- Resource owner: An entity capable of granting access to a protected resource. The "entity" is often a person - the end user.
- Resource server: The server hosting the protected resources.
- Client: An application making protected resource requests on behalf of the resource owner. This can for instance be a mobile application, a website or a background integration process impersonating an existing end user.
- Client credentials: a pair of client ID and client secret. This could be your developer or application ID and API key.
- Resource owner password credentials: the typical user-name/password combination issued to an end user.
OAuth2 flows
OAuth2 has four different modes of operating (called flows) - going from the relatively complex 3-legged authorization flow to the very simple "client credentials" authorization flow. At least one of the flows should fit into just about any public API ecosystem out there - and if not then it is possible to add new extension flows (as for instance Google does with the JWS implementation).
At its core OAuth2 has only two high level steps:
1) Swap a set of user and/or client credentials for an access token (authorization step), and
2) Use the access token to access the API resources.
That's it. It can be very simple. The difficult part of OAuth2 is the many ways a client can obtain an access token.
Here I will focus on a scenario with a trusted client that accepts user credentials and acts on behalf of them. This can be very useful for many internal integration patterns where no humans are involved. I won't cover the scenario where an untrusted client (third party website) needs to access the end user's resources using the 3-legged authorization flow.
Acces tokens and bearer tokens
At a suitable high level OAuth2 only has two steps as mentioned before: 1) authorization, 2) resource access. The output of a successful authorization step is always an access token which must be used in subsequent requests to the resource server (the API).
In most cases the access token is a so called "bearer token" - a token which the bearer can present to gain access to resources. Such a token has no built-in semantics and should be considered as nothing but a plain text string.
The bearer token is included in the HTTP Authorization header like this:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer SOME-TOKEN
Authorizing with client credentials only
This is just about the simplest flow possible (see http://tools.ietf.org/html/rfc6749#section-4.4): all the client has to do is to send it's client credentials (ID and secret) as if it was using HTTP basic authorization. In return the client receives an access token it can use in subsequent requests for the protected resources. Here is an example from the RFC:
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
The response could be:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer"
}
This flow allows the client to act on behalf of itself but it does not include any end user information.
Authorizing with both client credentials (API key) and user credentials (password)
If a client needs to act on behalf of the end user (the resource owner) then it can use the "Resource Owner Password Credentials Grant". This flow is almost as simple is the previous flow - all the client has to do is to add the client credentials to the authorization request. Here is an example from the RFC:
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w
The response could be:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer"
}
This flow allows the client to act on behalf of the end user. The client application must be trusted as the end user will have to pass his/her credentials to it.
Protecting credentials in transit
There is one big problem with the two simple flows mentioned above; both of them pass the client and end user credentials in clear text. For this reason OAuth2 makes it mandatory to use TLS/SSL to encrypt all of the requests. Neither does these flows cover scenarios with untrusted clients (such as a third party website that wants to access an end users resources on a different server) - but that scenario is covered in the "Authorization Code Grant" scenario which I will not discuss here.
The use of TLS/SSL protects the credentials from eavesdropping and man-in-the-middle attacks but it does not protect against sending credentials to the wrong server - either by misconfiguration or because the server has been compromised.
This lack of protection is perhaps one of the biggest difference between OAuth1 and OAuth2; OAuth1 protects credentials by signing requests instead of sending the raw credentials. This requires a rather complex signing algorithm which has caused many headaches over the time. OAuth2 trades the protection of credentials for simplicity which makes it a lot easier to use - but susceptible to leaking credentials to rogue servers.
It is possible to protect credentials from this problem though but it requires clients to use some complex crypto stuff to sign requests instead of sending the raw credentials (just like OAuth1 does). This is what Google does when it requires requests to be signed using JSON Web Signatures (JWS).
If you are using .NET then my Ramone HTTP library has support for OAuth2 with JWS as can be seen in this example: http://soabits.blogspot.com/2013/03/using-ramone-for-oauth2-authorization.html.
Protecting credentials in clients
One more word of caution - websites, mobile apps, desktop apps and similar with public clients cannot protect their client credentials. Other application may be able to do it (server to server integrations for instance) but public clients, be it JavaScript, byte code or assembler, can always be downloaded, decompiled and scrutinized by various forensic tools and in the end it will be impossible to keep client secrets from being stolen. This is a fact we have to live with.
Client credentials can be useful for statistics. They also give the ability to revoke credentials in order to block rogue applications - but they cannot be trusted in general.
Further reading
Eran Hammer has a discussion about the drawbacks of OAuth2 at http://hueniverse.com/2012/07/26/oauth-2-0-and-the-road-to-hell/ and here is another discussion of the drawbacks of bearer tokens http://hueniverse.com/2010/09/29/oauth-bearer-tokens-are-a-terrible-idea/torsdag, februar 20, 2014
Representing an issue tracker with Mason
Two weeks ago I introduced Mason - a media type for representing data with embedded hypermedia elements. Now I would like to go through an example implementation of a fictive issue tracker which uses Mason to represent its data.
At its core the issue tracker has, not surprisingly, "issues" that represent issues that needs to be solved. Issues are organized in projects and may have one or more file attachments associated with them. Issues are represented by their title, a description and a severity level (from 1 to 5).
It would be natural to include comments on issues too but I want to keep the domain as simple as possible while still being able to illustrate all the features of Mason - and comments would not add anything but clutter as they are very similar to attachments.
Please note that the issue tracker will be defined without reference to any existing implementation thus making it a "real" REST service totally independent of any specific implementation. I do have a reference implementation available but that is only used as a proof of concept - it is not part of the issue tracker definition itself.
The issue tracker is defined in terms of data types, links, link templates and actions as described in the next sections. That is not exactly interesting reading so you might want to skip it and jump to the later sections with examples of how to actually use the issue tracker.
You should try the demo issue tracker yourself with the generic Mason browser in order to see how actions and URL templates are supposed to work.
These URL relationship types ensures that we have no name collisions with other relationship types. In addition to this it is actually possible to dereference the URLs and GET some documentation about them.
Id: int
Title: string
Description: string
Severity: integer
Expected links:
Example resource: http://mason-issue-tracker.cbrain.net/issues/1
Issues: array of
- Id: int
- Title: string
Expected links:
Id: int
Code: string
Title: string
Description: string
Expected links:
Expected actions:
Projects: array of
- Id: int
- Code: string (a short code or abbreviation of the project name)
- Title: string
Expected links:
Example resource: http://mason-issue-tracker.cbrain.net/projects
Title: string (title of the whole issue tracker)
Description: string (description of the whole issue tracker)
Expected links:
Expected link templates:
Expected actions:
Example resource: http://mason-issue-tracker.cbrain.net/resource-common
Name: string
Address1: string
Address2: string
PostalCode: string
City: string
EMail: string
Phone: string
Country: string
Expected links:
text: any text to look for in issues.
severity: severity level (1-5)
pid: project ID.
Example usage: http://mason-issue-tracker.cbrain.net/resource-common
Code: string
Title: string
Description: string
Example usage: http://mason-issue-tracker.cbrain.net/resource-common
Code: string
Title: string
Description: string
Example usage: http://mason-issue-tracker.cbrain.net/projects/1
Example usage: http://mason-issue-tracker.cbrain.net/projects/1
Title: string
Description: string
Severity: int
Attachment: object of
- Title: string
- Description: string
In addition to this it is possible to pass a file as an attachment to the issue. The file name is "attachment".
The "Attachment" object contains additional information about the attached file.
Example usage: http://mason-issue-tracker.cbrain.net/projects/1
Title: string
Description: string
Severity: int
Example usage: http://mason-issue-tracker.cbrain.net/issues/1
Example usage: http://mason-issue-tracker.cbrain.net/issues/1
Title: string
Description: string
In addition to this it is possible to pass a file as the actual attachment. The file name is "attachment".
Example usage: http://mason-issue-tracker.cbrain.net/issues/1
Try it yourself: GET http://mason-issue-tracker.cbrain.net/resource-common
Here is an example:
"@actions": {
"is:project-create": {
"type": "json",
"href": "http://mason-issue-tracker.cbrain.net/projects",
"title": "Create new project",
"schemaUrl": "http://mason-issue-tracker.cbrain.net/schemas/create-project"
}
}
The most important parts are the "type" and "href" properties which tells us how to encode the data and where to send it. Mason actions also have a "method" property for identifying the HTTP method to use but it defaults to POST so its not always needed.
The type "json" tells us to encode the action arguments in plain JSON. The net result is a request like this:
POST /projects HTTP/1.1
Accept: application/vnd.mason+json
Content-Type: application/json
{
"Code": "SHOP",
"Title": "Webshop",
"Description": "Project for issues related to the webshop"
}
The response is a redirect to the created project:
HTTP/1.1 201 Created
Location: http://mason-issue-tracker.cbrain.net/projects/2
"@actions": {
"is:add-issue": {
"type": "json+files",
"href": "http://mason-issue-tracker.cbrain.net/projects/2/issues",
"title": "Add new issue to project",
"schemaUrl": "http://mason-issue-tracker.cbrain.net/schemas/create-issue",
"jsonFile": "args",
"files": [
{
"name": "attachment",
"description": "Attachment for issue"
}
]
}
}
This action tells us the following:
POST /projects/2/issues HTTP/1.1
Accept: application/vnd.mason+json
Content-Type: multipart/form-data; boundary=d636dfda-b79f-4f29-aaf6-4b6687baebeb
--d636dfda-b79f-4f29-aaf6-4b6687baebeb
Content-Disposition: form-data; name="attachment"; filename="hogweed.jpg"
... binary data for attached image ...
--d636dfda-b79f-4f29-aaf6-4b6687baebeb
Content-Disposition: form-data; name="args"; filename="args"
Content-Type: application/json
{
"Title": "Hogweeds on the plaza",
"Description": "Could you please remove the hogweeds growing at the plaza?",
"Severity": 5,
"Attachment":
{
"Title": "Hogweed",
"Description": "Photo of the hogweeds."
}
}
"@actions": {
"is:project-update": {
"type": "json",
"href": "http://mason-issue-tracker.cbrain.net/projects/1",
"title": "Update project details",
"template": {
"Code": "SHOP",
"Title": "Webshop",
"Description": "All issues related to the webshop."
}
}
}
This action tells us to encode project arguments in JSON and POST it to "http://mason-issue-tracker.cbrain.net/projects/1". The JSON data should be build from the JSON template in the action.
Request:
POST /projects/1 HTTP/1.1
User-Agent: API Explorer
Accept: application/vnd.mason+json
Content-Type: application/json
{
"Code": "SHOP",
"Title": "Web shop",
"Description": "All issues related to the new web shop."
}
"@actions": {
"is:project-delete": {
"type": "void",
"href": "http://mason-issue-tracker.cbrain.net/projects/1",
"method": "DELETE",
"title": "Delete project"
}
Request:
DELETE /projects/1 HTTP/1.1
Accept: application/vnd.mason+json
Response:
HTTP/1.1 204 No Content
"@link-templates": {
"is:issue-query": {
"template": "http://mason-issue-tracker.cbrain.net//issues-query?text={text}&severity={severity}&project={pid}",
"title": "Search for issues",
"description": "This is a simple search that do not check attachments.",
"parameters": [
{
"name": "text",
"description": "Substring search for text in title and description"
},
{
"name": "severity",
"description": "Issue severity (exact value, 1..5)"
},
{
"name": "pid",
"description": "Project ID"
}
]
}
}
This templates tells us to replace the parameters "text", "severity" and "pid" into the URL template "http://mason-issue-tracker.cbrain.net//issues-query?text={text}&severity={severity}&project={pid}".
Should we for instance want to query for issues of severity 5 in project 1 then we would get this request:
GET /issues-query?text=&severity=5&project=1 HTTP/1.1
Accept: application/vnd.mason+json
The result is a collection of issues.
At its core the issue tracker has, not surprisingly, "issues" that represent issues that needs to be solved. Issues are organized in projects and may have one or more file attachments associated with them. Issues are represented by their title, a description and a severity level (from 1 to 5).
It would be natural to include comments on issues too but I want to keep the domain as simple as possible while still being able to illustrate all the features of Mason - and comments would not add anything but clutter as they are very similar to attachments.
Please note that the issue tracker will be defined without reference to any existing implementation thus making it a "real" REST service totally independent of any specific implementation. I do have a reference implementation available but that is only used as a proof of concept - it is not part of the issue tracker definition itself.
The issue tracker is defined in terms of data types, links, link templates and actions as described in the next sections. That is not exactly interesting reading so you might want to skip it and jump to the later sections with examples of how to actually use the issue tracker.
You should try the demo issue tracker yourself with the generic Mason browser in order to see how actions and URL templates are supposed to work.
Data types, links and actions
CURIE definitions
In the following the CURIE name "is" should be expanded to "http://soabits.dk/mason/issue-tracker/reltypes.html#". So for instance "is:add-issue" becomes "http://soabits.dk/mason/issue-tracker/reltypes.html#add-issue" (you can GET that).These URL relationship types ensures that we have no name collisions with other relationship types. In addition to this it is actually possible to dereference the URLs and GET some documentation about them.
Data types
Issue
A single issue consists of the following properties:Id: int
Title: string
Description: string
Severity: integer
Expected links:
- self
- up: link to parent project
- is:attachments: link to collection of attachments for issue
- is:common: link to common resource data
Example resource: http://mason-issue-tracker.cbrain.net/issues/1
Issue collection
A collection of issues has one top level property:Issues: array of
- Id: int
- Title: string
Expected links:
- self
- up: link to parent project
- is:common: link to common resource data
Project
A single project consists of the following properties:Id: int
Code: string
Title: string
Description: string
Expected links:
- self
- is:issues: link to collection of issues for project
- is:common: link to common resource data
Expected actions:
- is:project-update
- is:add-issue
- is:project-delete
Project collection
A collection of projects has one top level property:Projects: array of
- Id: int
- Code: string (a short code or abbreviation of the project name)
- Title: string
Expected links:
- self
- is:common: link to common resource data
Example resource: http://mason-issue-tracker.cbrain.net/projects
Common resource data
A set of properties and links which are common to all resources:Title: string (title of the whole issue tracker)
Description: string (description of the whole issue tracker)
Expected links:
- self
- is:contact: link to contact information
- is:logo: link to issue tracker logo
- is:projects: link to collection of all projects
- is:common: link to common resource data
Expected link templates:
- is:issue-query
Expected actions:
- is:project-create
Example resource: http://mason-issue-tracker.cbrain.net/resource-common
Contact information
Contact information (related to the owner of the issue tracker) consists of:Name: string
Address1: string
Address2: string
PostalCode: string
City: string
EMail: string
Phone: string
Country: string
Expected links:
- self
- alternate (alternate address representations in other formats like for instance text/vcard)
- is:common
Link relations
is:projects
Link to collection of all projects.is:issues
Link to collection of issues for a given project.is:attachments
Link to collection of attachments for a given issue.is:contact
Link to contact information.is:logo
Link to issue tracker logo.is:common
Link to data common for all resources in the issue tracker.Link templates
is:issue-query
A link template for querying issues. Parameters:text: any text to look for in issues.
severity: severity level (1-5)
pid: project ID.
Example usage: http://mason-issue-tracker.cbrain.net/resource-common
Actions
is:project-create
Action for creating a new project. Arguments:Code: string
Title: string
Description: string
Example usage: http://mason-issue-tracker.cbrain.net/resource-common
is:project-update
Action for updating a single project. Arguments:Code: string
Title: string
Description: string
Example usage: http://mason-issue-tracker.cbrain.net/projects/1
is:project-delete
Action for deleting a project. Has no arguments.Example usage: http://mason-issue-tracker.cbrain.net/projects/1
is:add-issue
Action for adding a new issue to a project. Arguments:Title: string
Description: string
Severity: int
Attachment: object of
- Title: string
- Description: string
In addition to this it is possible to pass a file as an attachment to the issue. The file name is "attachment".
The "Attachment" object contains additional information about the attached file.
Example usage: http://mason-issue-tracker.cbrain.net/projects/1
is:issue-update
Action for updating a single issue. Arguments:Title: string
Description: string
Severity: int
Example usage: http://mason-issue-tracker.cbrain.net/issues/1
is:issue-delete
Action for deleting a single issue. Has no arguments.Example usage: http://mason-issue-tracker.cbrain.net/issues/1
is:add-attachment
Action for adding an attachment to an issue. Arguments:Title: string
Description: string
In addition to this it is possible to pass a file as the actual attachment. The file name is "attachment".
Example usage: http://mason-issue-tracker.cbrain.net/issues/1
Examples
Getting started
The first thing a client must do in order to work with the issue tracker is to GET the "common" resource that contains useful links, templates and actions for the issue tracker. The common resource can be thought of as the "home page" or "landing page" of the issue tracker.Try it yourself: GET http://mason-issue-tracker.cbrain.net/resource-common
Creating a new project
Once we have a copy of the "common" resource we can look for the action "is:project-create". That action will tell us how to encode the project data and how to submit it to the server.Here is an example:
"@actions": {
"is:project-create": {
"type": "json",
"href": "http://mason-issue-tracker.cbrain.net/projects",
"title": "Create new project",
"schemaUrl": "http://mason-issue-tracker.cbrain.net/schemas/create-project"
}
}
The most important parts are the "type" and "href" properties which tells us how to encode the data and where to send it. Mason actions also have a "method" property for identifying the HTTP method to use but it defaults to POST so its not always needed.
The type "json" tells us to encode the action arguments in plain JSON. The net result is a request like this:
POST /projects HTTP/1.1
Accept: application/vnd.mason+json
Content-Type: application/json
{
"Code": "SHOP",
"Title": "Webshop",
"Description": "Project for issues related to the webshop"
}
The response is a redirect to the created project:
HTTP/1.1 201 Created
Location: http://mason-issue-tracker.cbrain.net/projects/2
Adding a new issue
Now that we have a project we can start adding issues to it (with optional attachments). Each project representation contains an "is:add-issue" action for this purpose as can be seen here:"@actions": {
"is:add-issue": {
"type": "json+files",
"href": "http://mason-issue-tracker.cbrain.net/projects/2/issues",
"title": "Add new issue to project",
"schemaUrl": "http://mason-issue-tracker.cbrain.net/schemas/create-issue",
"jsonFile": "args",
"files": [
{
"name": "attachment",
"description": "Attachment for issue"
}
]
}
}
This action tells us the following:
- The type is "json+files" which means we must send the JSON data together with some files wrapped in the media type multipart/form-data.
- The target URL is "http://mason-issue-tracker.cbrain.net/projects/2/issues".
- The JSON data must conform to the schema definition at "http://mason-issue-tracker.cbrain.net/schemas/create-issue".
- The JSON data must be contained in a multipart element named "args".
- The attached file must be contained in a multipart element named "attachment".
POST /projects/2/issues HTTP/1.1
Accept: application/vnd.mason+json
Content-Type: multipart/form-data; boundary=d636dfda-b79f-4f29-aaf6-4b6687baebeb
--d636dfda-b79f-4f29-aaf6-4b6687baebeb
Content-Disposition: form-data; name="attachment"; filename="hogweed.jpg"
... binary data for attached image ...
--d636dfda-b79f-4f29-aaf6-4b6687baebeb
Content-Disposition: form-data; name="args"; filename="args"
Content-Type: application/json
{
"Title": "Hogweeds on the plaza",
"Description": "Could you please remove the hogweeds growing at the plaza?",
"Severity": 5,
"Attachment":
{
"Title": "Hogweed",
"Description": "Photo of the hogweeds."
}
}
Updating project details
Each project has a "is:project-update" action for updating the project details:"@actions": {
"is:project-update": {
"type": "json",
"href": "http://mason-issue-tracker.cbrain.net/projects/1",
"title": "Update project details",
"template": {
"Code": "SHOP",
"Title": "Webshop",
"Description": "All issues related to the webshop."
}
}
}
This action tells us to encode project arguments in JSON and POST it to "http://mason-issue-tracker.cbrain.net/projects/1". The JSON data should be build from the JSON template in the action.
Request:
POST /projects/1 HTTP/1.1
User-Agent: API Explorer
Accept: application/vnd.mason+json
Content-Type: application/json
{
"Code": "SHOP",
"Title": "Web shop",
"Description": "All issues related to the new web shop."
}
Deleting a project
Each project has a "is:project-delete" action for deleting the project and its related issues:"@actions": {
"is:project-delete": {
"type": "void",
"href": "http://mason-issue-tracker.cbrain.net/projects/1",
"method": "DELETE",
"title": "Delete project"
}
Request:
DELETE /projects/1 HTTP/1.1
Accept: application/vnd.mason+json
Response:
HTTP/1.1 204 No Content
Searching for issues
The "common" resource has a link template for issue queries:"@link-templates": {
"is:issue-query": {
"template": "http://mason-issue-tracker.cbrain.net//issues-query?text={text}&severity={severity}&project={pid}",
"title": "Search for issues",
"description": "This is a simple search that do not check attachments.",
"parameters": [
{
"name": "text",
"description": "Substring search for text in title and description"
},
{
"name": "severity",
"description": "Issue severity (exact value, 1..5)"
},
{
"name": "pid",
"description": "Project ID"
}
]
}
}
This templates tells us to replace the parameters "text", "severity" and "pid" into the URL template "http://mason-issue-tracker.cbrain.net//issues-query?text={text}&severity={severity}&project={pid}".
Should we for instance want to query for issues of severity 5 in project 1 then we would get this request:
GET /issues-query?text=&severity=5&project=1 HTTP/1.1
Accept: application/vnd.mason+json
The result is a collection of issues.
torsdag, februar 06, 2014
Implementing hypermedia APIs and REST services with Mason
I am happy to announce that I have taken all the lessons learned during the last few years and stuffed it into a new JSON based mediatype for hypermedia APIs and REST services. The media type is application/vnd.mason+json or simply "Mason". There is an IANA registration for it pending.
With Mason you get hypermedia elements for linking and modifying data, features for communicating to client developers and standardized error handling. Mason is built on JSON, reads JSON, writes JSON and generally fits well into a JSON based eco-system.
Here is a simple example illustrating how a single issue from a fictive issue tracker could be represented in Mason. It contains the basic API data like issue Title, Description and Severity and then it adds hypermedia elements for linking to other related resources and actions for writing stuff back to the issue tracker.
{
// Classic API data
"ID": 1,
"Title": "Program crashes when pressing ctrl-p",
"Description": "I pressed ctrl-p and, boom, it crashed.",
"Severity": 5,
"Attachments": [
{
"Id": 1,
"Title": "Error report",
// Hypermedia linking to attachment
"@links": {
"self": {
"href": "http://issue-tracker.org/attachments/1"
}
}
}
],
// Additional hypermedia links
"@links": {
// Hypermedia linking to self
"self": {
"href": "http://issue-tracker.org/issues/1"
},
// Hypermedia linking to containing project
"up": {
"href": "http://issue-tracker.org/projects/1",
"title": "Containing project"
},
},
// Hypermedia "action" element for creating a new project
"@actions": {
"is:project-create": {
"type": "json",
"href": "http://issue-tracker.org/mason-demo/projects",
"title": "Create new project",
"schemaUrl": "http://issue-tracker.org/mason-demo/schemas/create-project"
}
}
}
Those that are familiar with HAL may recognize some parts of the format. That is expected as Mason builds on the ideas from HAL. HAL was never intended to have hypermedia elements for writing stuff so I decided to go for it and design a new format based on HAL.
The Mason specification, online example and stand-alone API explorer are available from https://github.com/JornWildt/Mason.
My design goals with Mason are:
1. It should be easy to adopt in existing JSON based solutions and have a low barrier of entry for new developers.
2. It should contain hypermedia elements sufficient for both reading and writing data without any out-of-band information.
3. It should contain elements for information directed to client developers for the purpose of improving "API developer experience".
4. It should contain error elements sufficient for most kinds of applications.
5. It should work with JSON when both reading and writing.
Let me dig into each of those design goals one by one.
A classic JSON payload makes the raw API data directly accessible as JSON object properties. I believe it should be so too when working with hypermedia enabled APIs. So Mason merges hypermedia elements into existing JSON structures. To avoid name collisions Mason property names are prefixed with a '@'.
Mason can be adopted gradually:
Step 1: Change content type to application/vnd.mason+json instead of application/json.
Step 2: Add a @meta property with additional information targeted at client developers.
Step 3: Use links to remove client knowledge of server defined URLs.
Step 4: Use Mason's error format.
Step 5: Use actions to truly decouple client and server implementations.
Hypermedia has a lot of benefits as I wrote in http://soabits.blogspot.dk/2013/12/selling-benefits-of-hypermedia.html. Among these is the ability to remove a client's dependency on server URL structures using links.
But links are only good for, well, linking resources together - they don't say anything about how to change and modify API data. So Mason adds "actions" for writing API data.
An action defines both target URL, HTTP method and action type (payload encoding). With this information being discoverable at runtime it is no longer necessary to hard code clients with information about HTTP method and how to encode the payload. This means client and server only have to agree on WHICH data to send - not HOW to send it.
One of the great things about hypermedia enabled APIs is the ability to explore the API using a browser of some kind. As I wrote in http://soabits.blogspot.dk/2013/12/selling-benefits-of-hypermedia.html; Do not underestimate the power of an explorable API. The ability to browse around the data makes it a lot easier for the client developers to build a mental model of the API and its data structures.
And if client developers are browsing the API why not also be able to communicate directly with them? Mason adds a few meta data elements for sending messages directly to the client developers. An API browser should highlight these such that devs can instantly read some documentation and comments about the resource they are currently looking at.
At the same time Mason defines a technique for removing this client developer information from the payload in production.
By standardizing error handling Mason makes it possible for clients to interact with unknown services and still be able to communicate error conditions clearly to end users.
I have previously discussed error handling here in http://soabits.blogspot.dk/2013/05/error-handling-considerations-and-best.html and apparently that article hit a nerve somewhere because it keeps attracting a lot of attention (for an amateur blogger like me).
One of things that annoys me about the traditional key/value forms based on application/x-www-form-urlencoded is that there are no standards for encoding complex data structures. Neither does it define any standard for encoding booleans, integers and other basic data types. The consequence is that client and server needs to agree on these things before they can start talking about business data - and different servers are surely going to implement different encoding schemes - all in all making life miserable for developers that just want to get stuff done.
By using JSON Mason ensures interoperability on some of the lower levels. JSON defines more types than simple string based key/value formats and handles structures like objects and arrays.
Restricting implementations of Mason to handle JSON only reduces design choices and variations and thus improving the chances of things working out of the box (compared to simple string based key/value formats).
Most web APIs today are defined in terms of a single server implementation around which developers build dedicated clients (think "Twitter" or "Facebook"). In such a world clients have a strong coupling to server URL structures, HTTP methods, error formats and other quirks of the API. These APIs were never designed to be implemented by more than one organization (and are for this reason also called "snowflake APIs").
True REST services on the other hand are defined without reference to any specific server implementation. The best known example of this is the ATOM format which enables clients to interact with any ATOM enabled service on the web - no matter who implemented it, where it is hosted or what URL structures it is implemented with. The enabling factor for this is the ATOM media type specification.
But ATOM is restricted to feed-like data and does not fit well with other applications. So other media types are needed and Mason is an attempt to fill out this space. Mason attempts to facilitate complete decoupling from technical implementation details such that clients can discover HOW to interact with service at runtime.
One of my earlier blog posts discussed this problem in more detail: http://soabits.blogspot.no/2013/05/the-role-of-media-types-in-restful-web.html
Mason itself does not prescribe any business specific details. Clients and servers still have to agree on WHAT data to interchange - but Mason do remove the technical coupling on HOW to interchange the data.
Mason depends on profiles to enable clients to know WHAT data they are looking at. You can find an in-depth discussion about it here: http://soabits.blogspot.no/2013/12/media-types-for-apis.html.
At the time of writing I haven't put profiles into the specification yet.
Generic Mason browser (API explorer): https://github.com/JornWildt/Mason/wiki/Generic-Mason-browser
Online live example of fictive issue tracker using Mason: https://github.com/JornWildt/Mason/wiki/Example-service%3A-issue-tracker
/Jørn
With Mason you get hypermedia elements for linking and modifying data, features for communicating to client developers and standardized error handling. Mason is built on JSON, reads JSON, writes JSON and generally fits well into a JSON based eco-system.
Here is a simple example illustrating how a single issue from a fictive issue tracker could be represented in Mason. It contains the basic API data like issue Title, Description and Severity and then it adds hypermedia elements for linking to other related resources and actions for writing stuff back to the issue tracker.
{
// Classic API data
"ID": 1,
"Title": "Program crashes when pressing ctrl-p",
"Description": "I pressed ctrl-p and, boom, it crashed.",
"Severity": 5,
"Attachments": [
{
"Id": 1,
"Title": "Error report",
// Hypermedia linking to attachment
"@links": {
"self": {
"href": "http://issue-tracker.org/attachments/1"
}
}
}
],
// Additional hypermedia links
"@links": {
// Hypermedia linking to self
"self": {
"href": "http://issue-tracker.org/issues/1"
},
// Hypermedia linking to containing project
"up": {
"href": "http://issue-tracker.org/projects/1",
"title": "Containing project"
},
},
// Hypermedia "action" element for creating a new project
"@actions": {
"is:project-create": {
"type": "json",
"href": "http://issue-tracker.org/mason-demo/projects",
"title": "Create new project",
"schemaUrl": "http://issue-tracker.org/mason-demo/schemas/create-project"
}
}
}
Those that are familiar with HAL may recognize some parts of the format. That is expected as Mason builds on the ideas from HAL. HAL was never intended to have hypermedia elements for writing stuff so I decided to go for it and design a new format based on HAL.
The Mason specification, online example and stand-alone API explorer are available from https://github.com/JornWildt/Mason.
Design goals
My design goals with Mason are:
1. It should be easy to adopt in existing JSON based solutions and have a low barrier of entry for new developers.
2. It should contain hypermedia elements sufficient for both reading and writing data without any out-of-band information.
3. It should contain elements for information directed to client developers for the purpose of improving "API developer experience".
4. It should contain error elements sufficient for most kinds of applications.
5. It should work with JSON when both reading and writing.
Let me dig into each of those design goals one by one.
1. Easy to adopt
A classic JSON payload makes the raw API data directly accessible as JSON object properties. I believe it should be so too when working with hypermedia enabled APIs. So Mason merges hypermedia elements into existing JSON structures. To avoid name collisions Mason property names are prefixed with a '@'.
Mason can be adopted gradually:
Step 1: Change content type to application/vnd.mason+json instead of application/json.
Step 2: Add a @meta property with additional information targeted at client developers.
Step 3: Use links to remove client knowledge of server defined URLs.
Step 4: Use Mason's error format.
Step 5: Use actions to truly decouple client and server implementations.
2. Hypermedia for both reading and writing
Hypermedia has a lot of benefits as I wrote in http://soabits.blogspot.dk/2013/12/selling-benefits-of-hypermedia.html. Among these is the ability to remove a client's dependency on server URL structures using links.
But links are only good for, well, linking resources together - they don't say anything about how to change and modify API data. So Mason adds "actions" for writing API data.
An action defines both target URL, HTTP method and action type (payload encoding). With this information being discoverable at runtime it is no longer necessary to hard code clients with information about HTTP method and how to encode the payload. This means client and server only have to agree on WHICH data to send - not HOW to send it.
3. Information targeted at client developers
One of the great things about hypermedia enabled APIs is the ability to explore the API using a browser of some kind. As I wrote in http://soabits.blogspot.dk/2013/12/selling-benefits-of-hypermedia.html; Do not underestimate the power of an explorable API. The ability to browse around the data makes it a lot easier for the client developers to build a mental model of the API and its data structures.
And if client developers are browsing the API why not also be able to communicate directly with them? Mason adds a few meta data elements for sending messages directly to the client developers. An API browser should highlight these such that devs can instantly read some documentation and comments about the resource they are currently looking at.
At the same time Mason defines a technique for removing this client developer information from the payload in production.
4. Error handling
By standardizing error handling Mason makes it possible for clients to interact with unknown services and still be able to communicate error conditions clearly to end users.
I have previously discussed error handling here in http://soabits.blogspot.dk/2013/05/error-handling-considerations-and-best.html and apparently that article hit a nerve somewhere because it keeps attracting a lot of attention (for an amateur blogger like me).
5. JSON read/write
One of things that annoys me about the traditional key/value forms based on application/x-www-form-urlencoded is that there are no standards for encoding complex data structures. Neither does it define any standard for encoding booleans, integers and other basic data types. The consequence is that client and server needs to agree on these things before they can start talking about business data - and different servers are surely going to implement different encoding schemes - all in all making life miserable for developers that just want to get stuff done.
By using JSON Mason ensures interoperability on some of the lower levels. JSON defines more types than simple string based key/value formats and handles structures like objects and arrays.
Restricting implementations of Mason to handle JSON only reduces design choices and variations and thus improving the chances of things working out of the box (compared to simple string based key/value formats).
Transcending from web APIs to REST services
Most web APIs today are defined in terms of a single server implementation around which developers build dedicated clients (think "Twitter" or "Facebook"). In such a world clients have a strong coupling to server URL structures, HTTP methods, error formats and other quirks of the API. These APIs were never designed to be implemented by more than one organization (and are for this reason also called "snowflake APIs").
True REST services on the other hand are defined without reference to any specific server implementation. The best known example of this is the ATOM format which enables clients to interact with any ATOM enabled service on the web - no matter who implemented it, where it is hosted or what URL structures it is implemented with. The enabling factor for this is the ATOM media type specification.
But ATOM is restricted to feed-like data and does not fit well with other applications. So other media types are needed and Mason is an attempt to fill out this space. Mason attempts to facilitate complete decoupling from technical implementation details such that clients can discover HOW to interact with service at runtime.
One of my earlier blog posts discussed this problem in more detail: http://soabits.blogspot.no/2013/05/the-role-of-media-types-in-restful-web.html
Data profiles
Mason itself does not prescribe any business specific details. Clients and servers still have to agree on WHAT data to interchange - but Mason do remove the technical coupling on HOW to interchange the data.
Mason depends on profiles to enable clients to know WHAT data they are looking at. You can find an in-depth discussion about it here: http://soabits.blogspot.no/2013/12/media-types-for-apis.html.
At the time of writing I haven't put profiles into the specification yet.
Further reading
Mason homepage: https://github.com/JornWildt/MasonGeneric Mason browser (API explorer): https://github.com/JornWildt/Mason/wiki/Generic-Mason-browser
Online live example of fictive issue tracker using Mason: https://github.com/JornWildt/Mason/wiki/Example-service%3A-issue-tracker
/Jørn
søndag, december 08, 2013
Media types for APIs
I have previously touched upon the concept of media types (see http://soabits.blogspot.no/2013/05/the-role-of-media-types-in-restful-web.html), but somehow it has always been difficult for me to really nail the concept down in a concise and useful article.
Now the latest discussion about the benefits of hypermedia (see http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html) got me thinking about media types again - but this time in the perspective of unique service implementations with dedicated clients versus large scale ecosystems of mixed implementations.
As it turns out, media types doesn't mean sh*t on a small scale. That kind of explains why it has been so difficult to get to some kind of consensus about media types for APIs.
When the discussion touches upon media types the arguments usually follow these lines:
But, as I said, it really doesn't matter. Both schools are right. At least when you look at unique service implementations with dedicated clients - like for instance dedicated Twitter clients.
Let me give you a concrete example from the Twitter API (see https://dev.twitter.com/discussions/5662): the return value from their oauth/request_token "endpoint" is key/value pairs encoded as application/x-www-form-urlencoded - but the server says it is "text/html" which is clearly wrong. Does that break any client implementations? No. Why? Because all clients are dedicated to the Twitter API; they KNOW about this little peculiarity and has been hard coded to work with it.
My point is:
Let us broaden our view and look at the example of "Big corporation buys smaller companies and the result is a big unruly combination of customers, sales orders and other stuff living on different systems" which I introduced in my previous blog post (http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html).
Now lets assume our fictive client is handed a link/URL to a customer resource in this mess of a heterogeneous mix of different company resources. The client can issue a GET on the URL and in return it will receive a stream of bytes. How does the client interpret those bytes? Obviously it will depend on the media type. But which kind of media type is useful for this purpose?
Let us assume the client understand a generic (hypermedia enabled) media type like HAL. Together with the GET request the client sends an accept header "Accept: application/hal+json". Luckily the server knows how to serve the customer resource as HAL, so the client gets a HAL document in return.
Now what? We have integrated customer resources from three different organizations and each of these have been encoding customer records in HAL - but in different ways.
For instance: Company X has these customer properties:
{
ID: 1234,
Name: "John Larsson",
Address: "Marienborg 1, 2830 Virum, Denmark"
}
while company Y uses these properties:
{
ID: 1234,
FirstName: "John",
LastName: "Larsson",
Address:
{
Address: "Marienborg 1",
PostalCode: "2830",
City: "Virum",
Country: "Denmark"
}
}
With nothing but this information our client must either give up or do some guessing like "If FirstName is present then assume format of company Y". So apparently we need a bit more information than we already have.
Now we can either choose to add some kind of profile to the representation - either as a header or in the payload - or we can use a domain specific media type.
1) A profile in the payload could be done like this:
{
ID: 1234,
profile: "http://company-x.com/profiles/customer-care",
... other properties ...
}
2) The profile could also be part of the media type, so we would get "application/hal+json;profile=http://company-x.com/profiles/customer-care".
3) A domain specific media type could be something like "application/company-x.customer-care.hal+json" or similar.
But which method should we choose? Lets take a look at how the client process the server response before we answer that.
There are three things the client must know in order to process a server response correctly:
The media type is obviously the key to decoding the byte stream - it will tell the client whether it is looking at XML, PDF, HTML, HAL, Sirene and so on.
The media type should also be the key to locating hypermedia elements in the response.
But what about the domain specific knowledge - should we identify what a resource represents with a domain specific media type or with a profile? Both methods work, but there is one more thing to take into account: making the API explorable by client developers (see http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html).
It is of course possible to implement a browser for any domain specific media type we can think of, but it would obviously be more practical if we could have one single API browser for all kinds of APIs. For this reason we should avoid domain specific media types. The domain knowledge can then be identified by a profile - either in the payload or in a HTTP header.
As with the hypermedia problem: if you stick to unique service implementations with dedicated clients (like a dedicated Twitter client) then media types are utterly irrelevant. The client can safely assume that there will be one, and only one, representation of what ever kind of resource it is looking for.
But if you take broader perspective and venture into a highly heterogeneous, loosely coupled, unorganized, incoherent and fragmented ecology (also called "The internet") - then you need more domain specific information about the resources - either through domain specific media types, or generic media types with profiles.
My recommendation is:
The media type will tell the client HOW to decode the byte stream and HOW to interact with the resource. The profile will tell the client WHAT it is looking at.
Now the latest discussion about the benefits of hypermedia (see http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html) got me thinking about media types again - but this time in the perspective of unique service implementations with dedicated clients versus large scale ecosystems of mixed implementations.
As it turns out, media types doesn't mean sh*t on a small scale. That kind of explains why it has been so difficult to get to some kind of consensus about media types for APIs.
Background
When the discussion touches upon media types the arguments usually follow these lines:
- Completely generic media types like JSON and XML should be avoided since they do not include any kind of hypermedia elements.
- One school of thought argues that we should have very few (generic) media types. This is to avoid the need for clients to understand too many media types.
- Another school of thought argues that we should have many different domain specific media types. Otherwise the client wouldn't know what kind of resource it was looking at.
But, as I said, it really doesn't matter. Both schools are right. At least when you look at unique service implementations with dedicated clients - like for instance dedicated Twitter clients.
Let me give you a concrete example from the Twitter API (see https://dev.twitter.com/discussions/5662): the return value from their oauth/request_token "endpoint" is key/value pairs encoded as application/x-www-form-urlencoded - but the server says it is "text/html" which is clearly wrong. Does that break any client implementations? No. Why? Because all clients are dedicated to the Twitter API; they KNOW about this little peculiarity and has been hard coded to work with it.
My point is:
Media types are irrelevant for unique service implementations with dedicated clients. In this world the client always knows exactly what it is doing and what kind of result to expect from the server (and it can safely ignore the media type).
Media types on a large scale
Let us broaden our view and look at the example of "Big corporation buys smaller companies and the result is a big unruly combination of customers, sales orders and other stuff living on different systems" which I introduced in my previous blog post (http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html).
Now lets assume our fictive client is handed a link/URL to a customer resource in this mess of a heterogeneous mix of different company resources. The client can issue a GET on the URL and in return it will receive a stream of bytes. How does the client interpret those bytes? Obviously it will depend on the media type. But which kind of media type is useful for this purpose?
Let us assume the client understand a generic (hypermedia enabled) media type like HAL. Together with the GET request the client sends an accept header "Accept: application/hal+json". Luckily the server knows how to serve the customer resource as HAL, so the client gets a HAL document in return.
Now what? We have integrated customer resources from three different organizations and each of these have been encoding customer records in HAL - but in different ways.
For instance: Company X has these customer properties:
{
ID: 1234,
Name: "John Larsson",
Address: "Marienborg 1, 2830 Virum, Denmark"
}
while company Y uses these properties:
{
ID: 1234,
FirstName: "John",
LastName: "Larsson",
Address:
{
Address: "Marienborg 1",
PostalCode: "2830",
City: "Virum",
Country: "Denmark"
}
}
With nothing but this information our client must either give up or do some guessing like "If FirstName is present then assume format of company Y". So apparently we need a bit more information than we already have.
Now we can either choose to add some kind of profile to the representation - either as a header or in the payload - or we can use a domain specific media type.
1) A profile in the payload could be done like this:
{
ID: 1234,
profile: "http://company-x.com/profiles/customer-care",
... other properties ...
}
2) The profile could also be part of the media type, so we would get "application/hal+json;profile=http://company-x.com/profiles/customer-care".
3) A domain specific media type could be something like "application/company-x.customer-care.hal+json" or similar.
But which method should we choose? Lets take a look at how the client process the server response before we answer that.
Processing a server response
There are three things the client must know in order to process a server response correctly:
- How to decode the byte stream (generic knowledge).
- What the data represents (domain specific knowledge).
- How to locate hypermedia elements in the response (generic knowledge).
The media type is obviously the key to decoding the byte stream - it will tell the client whether it is looking at XML, PDF, HTML, HAL, Sirene and so on.
The media type should also be the key to locating hypermedia elements in the response.
But what about the domain specific knowledge - should we identify what a resource represents with a domain specific media type or with a profile? Both methods work, but there is one more thing to take into account: making the API explorable by client developers (see http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html).
It is of course possible to implement a browser for any domain specific media type we can think of, but it would obviously be more practical if we could have one single API browser for all kinds of APIs. For this reason we should avoid domain specific media types. The domain knowledge can then be identified by a profile - either in the payload or in a HTTP header.
Wrapping it all up
As with the hypermedia problem: if you stick to unique service implementations with dedicated clients (like a dedicated Twitter client) then media types are utterly irrelevant. The client can safely assume that there will be one, and only one, representation of what ever kind of resource it is looking for.
But if you take broader perspective and venture into a highly heterogeneous, loosely coupled, unorganized, incoherent and fragmented ecology (also called "The internet") - then you need more domain specific information about the resources - either through domain specific media types, or generic media types with profiles.
My recommendation is:
- Use generic media types that include hypermedia elements.
- Identify domain specific information through profiles.
The media type will tell the client HOW to decode the byte stream and HOW to interact with the resource. The profile will tell the client WHAT it is looking at.
fredag, december 06, 2013
Selling the benefits of hypermedia in APIs
Once more I have found myself deeply engaged in a discussion about REST on the api-craft mailing list (https://groups.google.com/forum/#!topic/api-craft/ZxnLD6q6w7w). This time it started with the question "How do I sell the benefits of hypermedia". It turned out to be harder to answer than one would expect, but after some time we came up with the list below. But before we get into that I better explain "hypermedia" in a few sentences.
The most common use of hypermedia is embedding of links in representations returned from some service on the web. As an example we can look at the representation of a customer record containing a customer ID, customer name, customer contact information and related sales orders. Encoded in JSON we can get something like this:
// Customer record
// URL template: http://company-x.com/customers/{customer-id}
{
ID: 1234,
Name: "John Larsson",
Address: "Marienborg 1, 2830 Virum, Denmark",
}
// List of sales order
// URL template: http://company-x.com/customers/{customer-id}/sales-orders
{
CustomerId: 1234,
Orders:
[
{
ID: 10,
ItemNumber: 15,
Quantity: 4
}
]
}
These two resources can be found by expanding the customer ID into the URL templates. This requires the client to be hard coded with 1) the URL templates and 2) the knowledge of which values to use as parameters.
Now, if we embed links in the responses then we can remove the hard coded knowledge of at least the sales orders URL template:
// Customer record
// URL template: http://company-x.com/customers/{customer-id}
{
ID: 1234,
Name: "John Larsson",
Address: "Marienborg 1, 2830 Virum, Denmark",
_links:
[
{
rel: "http://linkrels.company-x.com/sales-orders",
href: "{link-to-sales-orders}",
title = "Sales orders"
}
]
}
// List of sales order
// URL template unpublished
{
CustomerId: 1234,
Orders:
[
{
ID: 10,
ItemNumber: 15,
Quantity: 4,
_links:
[
{
rel: "http://linkrels.company-x.com/order-details",
href: "{link-to-sales-order-details}",
title = "Sales order details"
},
{
rel: "http://linkrels.company-x.com/item-details",
href: "{link-to-item-details}",
title = "Item order details (catalog)"
}
]
}
]
}
Notice how links are encoded:
The question is know, what is gained by adding such links?
Think of it like this; traditionally, as a client developer, you would have to read through a pile of documentation before you sit down and write some test programs more or less blindfolded. After that you run your test program to see how the API behaves. Then you have to go back to the documentation and read some more - and then back to coding again. This exercise has three different mental context switches going back and forth between reading documentation, programming and trying out test programs.
With an explorable API you can simply try out the API and test your understanding of it without any programming. Any mental "what-if" hypothesis testing of the API can be carried out right there without any additional tools or programming. The data as well as the interaction tools is right there in front of you, reducing the mental hoops you have to go through to understand the API.
The immediate benefits of an explorable API is perhaps more social than technical. But mind you - a lower barrier of entry means happier client developers, higher API adoption rates and less support, which in the end means fewer annoying support calls to bug YOU at the most annoying times of your work.
The immediate benefits of this are also social just like the explorability of the API. It will lower the barrier of entry to understanding the API and improve API adoption by client developers.
The benefits of this is obviously less coupling between the server and the client, removing the need to upgrade all clients in lock step with the server.
But, you may ask, why should the server change its URL structures? Once the server developers has decided that the URL is /customers/{customer-id} why should they then suddenly decide to change it? Well, I cannot tell you what will change in your API, but here are two examples:
- A resource grows too big. Over time it has been necessary to add more and more features to a single resource and one day it simply becomes too big to handle. So it is decided to split it into multiple sub-resources with new URL structures.
- It turns out that some resources requires bits and pieces of information from other resources when the client access them. It can for instance be an access token of some kind that need to be generated in one place and passed to another resource. With a traditional API the client has to be upgraded with this kind of business logic. With a hypermedia API the client can ignore this complexity and leave it to the server to add the desired parameters to the links it generates.
Hypermedia also allows the server to re-implement an existing resource with a completely different technology stack, on a completely different server, without the client ever noticing it - given, of course, that the new implementation doesn't make any breaking changes.
If you want to read more about versioning then take a look at Mark Nottingham's "Web API versioning smackdown" at http://www.mnot.net/blog/2011/10/25/web_api_versioning_smackdown
Let us try to broaden the scene: think of a big corporation that has engulfed and bought up a lot of smaller companies. All of these smaller companies have their own server setup with lists of inventory, sales orders, customers and so on ...
Now I give you the ID 4328 of customer John Burton ... how will you be able to find the resource that represent the contact information of this customer, when it can live on any one of a dozen servers?
Solution 1: We need a central indexing service that allows the client to search for customer with ID 4328. But how can the indexing service tell the client where the resulting customer record resides? The answer is simple; the response has to contain a link to the customer record resource.
Solution 2: Don't use IDs like 4328 at all. Always refer to resources with their full URLs.
Either way, the client won't know anything about the URL it gets in return - all it has to do is to trust the search result and follow the link.
And now that we have some opaque, meaningless, URL to our customer record information, how do we get to the sales orders placed by said customer? We could take the customer ID again and throw it into some other indexing service and get a new URL out of it - or we could follow a "sales-orders" link-relation embedded in the customer information.
The point is:
I have already written about error handling in http://soabits.blogspot.no/2013/05/error-handling-considerations-and-best.html where the last section discuss error handling on a larger scale.
Unfortunately I have yet to write an article explaining my current view on media types - until then you can either check this post in api-craft https://groups.google.com/d/msg/api-craft/5N5SS0JMAJw/b0diFRzopY0J or read my ramblings about media types and type systems http://soabits.blogspot.no/2013/05/the-role-of-media-types-in-restful-web.html.
UPDATE (December 8th 2013): I have just added a blog post about media types: http://soabits.blogspot.no/2013/12/media-types-for-apis.html
The most common use of hypermedia is embedding of links in representations returned from some service on the web. As an example we can look at the representation of a customer record containing a customer ID, customer name, customer contact information and related sales orders. Encoded in JSON we can get something like this:
// Customer record
// URL template: http://company-x.com/customers/{customer-id}
{
ID: 1234,
Name: "John Larsson",
Address: "Marienborg 1, 2830 Virum, Denmark",
}
// List of sales order
// URL template: http://company-x.com/customers/{customer-id}/sales-orders
{
CustomerId: 1234,
Orders:
[
{
ID: 10,
ItemNumber: 15,
Quantity: 4
}
]
}
These two resources can be found by expanding the customer ID into the URL templates. This requires the client to be hard coded with 1) the URL templates and 2) the knowledge of which values to use as parameters.
Now, if we embed links in the responses then we can remove the hard coded knowledge of at least the sales orders URL template:
// Customer record
// URL template: http://company-x.com/customers/{customer-id}
{
ID: 1234,
Name: "John Larsson",
Address: "Marienborg 1, 2830 Virum, Denmark",
_links:
[
{
rel: "http://linkrels.company-x.com/sales-orders",
href: "{link-to-sales-orders}",
title = "Sales orders"
}
]
}
// List of sales order
// URL template unpublished
{
CustomerId: 1234,
Orders:
[
{
ID: 10,
ItemNumber: 15,
Quantity: 4,
_links:
[
{
rel: "http://linkrels.company-x.com/order-details",
href: "{link-to-sales-order-details}",
title = "Sales order details"
},
{
rel: "http://linkrels.company-x.com/item-details",
href: "{link-to-item-details}",
title = "Item order details (catalog)"
}
]
}
]
}
Notice how links are encoded:
- Links are always found in collections named _links
- A single link consists of a link relation identifier "rel", the hypermedia reference "href" and a human readable description "title".
- Link relations are identified by URLs.
The question is know, what is gained by adding such links?
Short term effects
1. Explorable API
It may sound trivial but do not underestimate the power of an explorable API. The ability to browse around the data makes it a lot easier for the client developers to build a mental model of the API and its data structures.Think of it like this; traditionally, as a client developer, you would have to read through a pile of documentation before you sit down and write some test programs more or less blindfolded. After that you run your test program to see how the API behaves. Then you have to go back to the documentation and read some more - and then back to coding again. This exercise has three different mental context switches going back and forth between reading documentation, programming and trying out test programs.
With an explorable API you can simply try out the API and test your understanding of it without any programming. Any mental "what-if" hypothesis testing of the API can be carried out right there without any additional tools or programming. The data as well as the interaction tools is right there in front of you, reducing the mental hoops you have to go through to understand the API.
The immediate benefits of an explorable API is perhaps more social than technical. But mind you - a lower barrier of entry means happier client developers, higher API adoption rates and less support, which in the end means fewer annoying support calls to bug YOU at the most annoying times of your work.
2. Inline documentation
Did you notice how link relations are identified by URLs? These URLs can point to online documentation where the API elements can be explained.The immediate benefits of this are also social just like the explorability of the API. It will lower the barrier of entry to understanding the API and improve API adoption by client developers.
3. Simple client logic
A client that simply follows URLs instead of constructing them itself, should be easier to implement and maintain. It won't need logic to figure out which values to substitute into what URL templates. All it has to do is to identify links in the payload and extract the hypermedia reference URL.Long term effects
4. The server takes ownership of URL structures
The use of hypermedia removes the client's hard coded knowledge of the URL structures used by the server. This means the server is free to change its URL structures over time when the API evolves without any need to upgrade the clients.The benefits of this is obviously less coupling between the server and the client, removing the need to upgrade all clients in lock step with the server.
But, you may ask, why should the server change its URL structures? Once the server developers has decided that the URL is /customers/{customer-id} why should they then suddenly decide to change it? Well, I cannot tell you what will change in your API, but here are two examples:
- A resource grows too big. Over time it has been necessary to add more and more features to a single resource and one day it simply becomes too big to handle. So it is decided to split it into multiple sub-resources with new URL structures.
- It turns out that some resources requires bits and pieces of information from other resources when the client access them. It can for instance be an access token of some kind that need to be generated in one place and passed to another resource. With a traditional API the client has to be upgraded with this kind of business logic. With a hypermedia API the client can ignore this complexity and leave it to the server to add the desired parameters to the links it generates.
5. Off loading content to other services
Consider how APIs evolve: after some time you figure out that some of the content should be off-loaded to a Content Delivery Network (CDN). This means new URLs that points to completely different hosts all over the internet. The actual URL cannot be hard coded into the client since it may change over time or contain random pieces of server generated information for the CDN (like for instance some kind of access token). Now the server HAS to embed the URLs in the responses and the client HAS to follow them.6. Versioning with links
With a hypermedia API it becomes trivial to implement new versions of the API resources without breaking existing clients: old clients will follow existing link relations to old-style resources whereas new clients will know how to follow new link relations to new resources - as long as the server response includes both the old as well as the new links.Hypermedia also allows the server to re-implement an existing resource with a completely different technology stack, on a completely different server, without the client ever noticing it - given, of course, that the new implementation doesn't make any breaking changes.
If you want to read more about versioning then take a look at Mark Nottingham's "Web API versioning smackdown" at http://www.mnot.net/blog/2011/10/25/web_api_versioning_smackdown
Large scale effects
7. Multiple implementations of the same service
So far we have only looked at clients dedicated to a unique implementation of a single service. That could for instance be something kike a dedicated Twitter client. But where hypermedia really excels is when we start to work with multiple independent implementations of the same service.Let us try to broaden the scene: think of a big corporation that has engulfed and bought up a lot of smaller companies. All of these smaller companies have their own server setup with lists of inventory, sales orders, customers and so on ...
Now I give you the ID 4328 of customer John Burton ... how will you be able to find the resource that represent the contact information of this customer, when it can live on any one of a dozen servers?
Solution 1: We need a central indexing service that allows the client to search for customer with ID 4328. But how can the indexing service tell the client where the resulting customer record resides? The answer is simple; the response has to contain a link to the customer record resource.
Solution 2: Don't use IDs like 4328 at all. Always refer to resources with their full URLs.
Either way, the client won't know anything about the URL it gets in return - all it has to do is to trust the search result and follow the link.
And now that we have some opaque, meaningless, URL to our customer record information, how do we get to the sales orders placed by said customer? We could take the customer ID again and throw it into some other indexing service and get a new URL out of it - or we could follow a "sales-orders" link-relation embedded in the customer information.
The point is:
When you transcend from unique one-off service implementations with dedicated clients to multiple independent service implementations with a variety of clients then you simply have to use hypermedia elements.This also means that it can be difficult to sell hypermedia to startup APIs since hypermedia won't add much benefit to one single API living on a isolated island without any requirements of being able to co-exists and co-work seamlessly with other similar services.
Other large scale effects
Hypermedia solves some of the problems related to large scale service implementations as I have just argued. But there are a few more issues to be solved in order to decouple clients completely from specific server implementations; one is related to how the client understands the result (media types) and one is related to error handling.I have already written about error handling in http://soabits.blogspot.no/2013/05/error-handling-considerations-and-best.html where the last section discuss error handling on a larger scale.
Unfortunately I have yet to write an article explaining my current view on media types - until then you can either check this post in api-craft https://groups.google.com/d/msg/api-craft/5N5SS0JMAJw/b0diFRzopY0J or read my ramblings about media types and type systems http://soabits.blogspot.no/2013/05/the-role-of-media-types-in-restful-web.html.
UPDATE (December 8th 2013): I have just added a blog post about media types: http://soabits.blogspot.no/2013/12/media-types-for-apis.html
Acknowledgments
Thanks to Mike Kelly for his initial blogpost on this tema: http://blog.stateless.co/post/68259564511/the-case-for-hyperlinks-in-apis - and his work on hypermedia linking in JSON with HAL (http://stateless.co/hal_specification.html).onsdag, oktober 02, 2013
URL structures and hyper media for Web APIs and RESTful services
A recurring theme on various mailing lists is that of choosing the "right" URL structure for a specific kind of web API. In this post I will present my view on this issue, based on various input from for instance "API-craft" (https://groups.google.com/forum/#!forum/api-craft).
First of all, let me hammer it in: URL structuring has absolutely nothing to do with REST. Period. REST is not concerned about URL structures - in REST a URL is an opaque string of characters with no meaning beyond the fact that it is both an identifier and a resource locator. An on-line web service doesn't become a RESTful service just because it has a nice pretty looking URL structure. There is simply no such thing as "A RESTful URL".
What this means is that a URL like http://geo.com/countries/usa/states/nevada is just as "RESTful" (or non-RESTful) as http://geo.com/states/nevada, http://geo.com/states/321, http://geo.com/states?id=321 and http://geo.com/foo-bar-U7q. The URL structure simply doesn't matter in REST.
But from a human point of view it helps understanding if the API has some kind of meaningful URL structure. Computers may easily ignore URL structures but as humans we tend to look at URLs and try to infer meaning from that. Thus, having pretty and well structured URLs helps us understand what is going on - not only as client developers but certainly also as server developers who often have to navigate from URLs to source code - and having a well defined URL structure helps us with that process.
In order to discuss URL structures we need a domain to model. I think geographical information with countries, states and cities should be easily understood by most, so lets try that. I will ignore the fact that many countries doesn't have states ;-)
/countries/USA/states/Nevada/cities/Las+Vegas
That would work, but think a bit about it; what if the state of Nevada had more than one city called Las Vegas? How would we be able to distinguish between the two cities? The problem here is that we confuse searching for a city named Las vegas in Nevada, USA with the concept of identifying a specific city.
I believe that it is fair to assume that most geographical systems will have some kind of backend that assigns unique identifies to all of its entities. This may be integers, GUIDs or strings with composite keys - but in the end it boils down to a sequence of characters that uniquely identifies the entity in the system.
So let us assume that the well known city of Las Vegas is identified by the integer 82137 which is a unique city number. It may happen to be the same number which is used for a country or a state, but in the context of cities it is unique.
The same goes for countries and states: USA has the ID 54 and Nevada is identified by 7334. Now we get the URL:
/countries/54/states/7334/cities/82137
But what happens if some client decided to lookup this URL with mismatching IDs:
/countries/54/states/8112/cities/82137
Well, that should be considered a non existing resource and the server should return HTTP code 404 Not Found.
But why bother at all with the overhead of checking both state, country and city IDs when the city ID uniquely identifies the city? It would be easier for all parties if only the city ID was needed in the URL:
/cities/82137
Now the server can do one single lookup by the ID to see if the referenced city exists. No need for any additional checking for matching state and country.
The same logic can be applied to states (and countries is trivial), so we end up with the following canonical URL structures for countries, states and cities:
/countries/{country-id}
/states/{state-id}
/cities/{city-id}
Should it happen that the server doesn't assign unique IDs to cities (or states), and really needs the state reference for a city, because two cities in different states may have the same (non-unique) ID, then we must include both in the URL:
/states/123/cities/77 => Rome in Italy (assuming some state in Italy is identified by 123)
/states/432/cities/77 => Rome in the state of New York
In the rest of this post I will assume that all cities and states has "globally" unique IDs.
The UI could be structured by three dropdowns: one for countries, one for states in the selected country and one for cities in the selected state. To present such a UI for the end user we first need to be able to get the list of all countries. The obvious choice for this resource is /countries. Then, for the selected country we need the list of states. The obvious choice here is /countries/{country-id}/states.
But what about the list of all cities for a specific state in a specific country? Let us avoid the trap of a hierarchical URL with multiple IDs and use the short /states/{state-id}/cities.
So now we have the following resources representing lists of geographical items:
/countries
/countries/{country-id}/states
/states/{state-id}/cities
Each of these resources returns a JSON list as shown below and from this list the UI can easily build a dropdown element for selecting a city:
[
{ Name: "Item name A", ID: xxx },
{ Name: "Item name B", ID: yyy }
]
In this way the client gets the unique city ID by letting the end user select a city and its corresponding ID.
/cities?query=Las+Vegas,+USA
The result would be a list of matching cities:
[
{ Title: "Las Vegas, County A, Nevada, USA", ID: 16352 },
{ Title: "Las Vegas, County B, Nevada, USA", ID: 82137 }
]
Now the end user can select one of the results and thus get the ID of the city.
But it is very easy to avoid this kind of URL coupling by using hyper media elements in the returned representations. Take for instance the list of cities matching the text "Las Vegas, USA"; here we can include the actual city URLs in the response instead of requiring the clients to construct the URLs itself:
[
{
Title: "Las Vegas, County A, Nevada, USA",
ID: 16352,
CityLink: "http://.../cities/16352"
},
{
Title: "Las Vegas, County B, Nevada, USA",
ID: 82137,
CityLink: "http://.../cities/82137"
}
]
Now we can start talking about a RESTful service instead of a static web API: by including hyper media elements we allow the server to include links to other hosts that might be better to represent cities:
[
{
Title: "Las Vegas, County A, Nevada, USA",
CityLink: "http://other-geo-service/jump.aspx?type=city&ID=16352"
},
{
Title: "Las Vegas, County B, Nevada, USA",
CityLink: "http://geo.com/cities/82137"
}
]
By including links we have stopped worrying about URL structures and has come one step closer to a RESTful service.
The upside is looser coupling to server URL structures, simpler client logic and enabling the use of different services on different servers. The downside is a larger payload with bigger URLs than simple IDs.
There are many different ways to do this depending on the complexity of the filtering. But it may be fine to start out with simple queries like "All cities in (Massachusetts or New York)"; first we need to use state IDs and thus we get "All cities in states (2321, 2981)". Such simple integer IDs can be separated with commas, so one possible URL structure could be:
/cities?states=2321,2981
It is also possible to encode an SQL like query language in one single parameter:
/cities?where=state+in+(2321,2981)+and+population+greater-than+200000
The possibilities are endless, but it usually consists of a path like /cities that identifies the type of query together with some set of URL parameters encoding the query specification.
A common solution is to interpret "&" as AND and "," as OR when possible. So for instance /cities?states=2321,2981&size=large,huge would mean "All cities where state is either (Massachusetts OR New Your) AND size is either (large OR huge)".
And no discussion about filtering without mentioning OData's URL conventions: http://www.odata.org/documentation/odata-v3-documentation/url-conventions/
POST /city-filters
Content-Type: application/x-www-form-urlencoded
where=state+in+(2321,2981)+and+population+greater-than+200000
The server then creates a temporary resource for this query and returns a redirect to it:
201 Created
Location: /city-filters/9638
The client can then GET /city-filters/9638 to get the result of the query.
A nice side effect of this is that the created filter resource can be cached to avoid re-calculating the potentially very slow query on the server.
When choosing between natural keys versus surrogate keys you should consider the lifespan of the key; URLs are supposed to be stable over a very long period of time, so do not choose keys that vary over time. For instance, do not use phone numbers and e-mails to identify people since people tend to change these during their life.
You should also beware of natural keys which can be used by more than one entity. It is for instance (still) common for some members of a family to share a common e-mail, so e-mails are not good candidates for identifying persons. Even social security numbers may sometimes change. In Denmark for instance a person may get a new social security number if they change gender.
A valid natural key could be a sales order number since these are supposed to be both unique and stable.
But if we introduce natural keys, should we then only use natural keys? What if an entity has both a natural key and an internal surrogate key? You can use both but you should decide on one being the canonical ID and avoid duplicating resources by using HTTP redirects for the secondary keys.
Take for instance a sales order with the order number SK324-1 and internal surrogate key 887766 - if we consider the order number as the canonical ID then we can use these URL structures:
/orders/SK324-1 => returns order representation
/orders/id/887766 => redirects to /orders/SK324-1
Redirects should be done using the HTTP status code 303 See Other with a Location header containing the canonical URL.
As stated earlier on: do not confuse searching with identity. You may want to search for a person with a specific e-mail, but the result should include the canonical URL of the found person.
See also http://www.w3.org/TR/webarch/#uri-aliases for a discussion of URL aliases and duplication.
/states/{state-id}/country
But, wait a minute, we already have links to countries, right? The canonical version is although /countries/{country-id} so how do we get from /states/{state-id}/country to /countries/{country-id}? The obvious answer is to consider the /states/{state-id}/country URL as an alias for some country and use HTTP redirects to get to the canonical country URL.
But lets step back and take a broader look at relations in general; a back-reference is just one kind of relation from one resource to another - but we could have many other kinds of relations, like "neighbor states", "the country of a city", "statistical information about a state" and so on. The general solution to this concept is to include links in the payloads instead of creating a myriade of small alias resources that only redirects to canonical URLs.
So, instead of using /states/{state-id}/country for the country of a certain state, we include the canonical country link in the representation of the state:
GET /states/4321
returns =>
{
Name: "State X",
CountryLink: "http://.../countries/1234",
NeighborStatesLink: "http://.../states/4321/neighbors"
}
Take for instance our state resource at /states/{state-id} - it may contain some very static data like the name of the state, its area and such like plus some volatile data like for instance the number of Tweets tweeted from that state the last ten minutes. The static information could easily be cached, but we have no way to do it since the complete resource also contains the number of Tweets.
The solution is straight forward: split the resource into two different resources:
/states/{state-id} => static state information
/states/{state-id}/tweet-stats => volatile tweet information
I'll admit that the above example is rather contrived, so lets try a more realistic example: a streaming music distribution network publishes information about its songs through an online web API. Each song has its own resource representation with details about the song. The title, lyrics, artist and such like won't change much (if ever), but the company also publishes the number of current listeners which changes all the time. To improve caching characteristics the song data is split into (at least) two different resources:
/songs/{song-id} => static song details (cacheable)
/songs/{song-id}/usage => volatile usage information (non cacheable)
But who says the song usage is published by the same API? Some time after the initial release of the web API the company off-load some of the streaming to another content delivery network which will also deliver the usage statistics. Now suddenly not only the URL structure changes but even the host name changes:
/songs/{song-id} => static song details (cacheable)
http://cdn.com/acme/file-usage/{song-id} => volatile usage information (non cacheable)
This is a breaking change and all clients must now be upgraded. Had the API instead contained hyper links then the change would have been transparent to all clients.
Classic song representation:
{
Id: 1234,
Name: "My song"
}
Hyper media improved representation:
{
Id: 1234,
Name: "My song",
UsageLink: "http://cdn.com/acme/file-usage/1234"
}
Once again we see how unimportant the actual URL structure is when we start using hyper media elements in the responses.
My recommendation is to implement the extensions as a convenience for the client developers, but avoid using them when interacting with the API "for real". If for instance our geographical API can return both JSON as well as XML and HTML then I would use these URLs for states:
/states/{state-id} => canonical URL used in all returned hyper media elements
/states/{state-id}.json => JSON representation of state
/states/{state-id}.xml => XML representation of state
/states/{state-id}.html => HTML representation of state
The canonical URL would also support standard HTTP content negotiation for JSON, XML and HTML representations of the exact same resource. The framework I use, OpenRasta, supports this dual type of "content negotiation" right out of the box with no implementation overhead.
If our resources have different variations then we can add them as "sub resources" of the primary resource (not that such a thing really exists since URLs are opaque strings). Where I work we have resources for documents in a case management system. These resources contains meta data about the document (title, owner and so on) - and then we have various other (sub) resources for the documents themselves - the raw binary document (image, power point, pdf etc.), a PDF replica of the document and a PDF replica with an added front page containing the document meta data. Thus we get these URLs:
/documents/{doc-id} => canonical document meta data URL
/documents/{doc-id}/pdf => PDF replica
/documents/{doc-id}/meta-pdf => PDF replica with meta data frontpage
In this way you will avoid the trap of doing something horrible like this which I would expect to delete order number 1234 when you GET the resource:
GET /orders/1234/delete
You also get the ability to identify all your resources and add caching, which is not possible with this sort of old school SOAP'ish look-up mechanism:
POST /orders
Body => { OrderId: 1234, Operation: "read" }
And you get a nice explorable and consistent API that you developers will love to use :-)
Well, API and URL versioning is a whole story in itself so I suggest you take a look at Mark Nottingham's excellent "API versioning smackdown" (http://www.mnot.net/blog/2011/10/25/web_api_versioning_smackdown) for a good discussion on this subject.
Have fun, hack some code and create beautiful APIs out there :-)
/Jørn
First of all, let me hammer it in: URL structuring has absolutely nothing to do with REST. Period. REST is not concerned about URL structures - in REST a URL is an opaque string of characters with no meaning beyond the fact that it is both an identifier and a resource locator. An on-line web service doesn't become a RESTful service just because it has a nice pretty looking URL structure. There is simply no such thing as "A RESTful URL".
What this means is that a URL like http://geo.com/countries/usa/states/nevada is just as "RESTful" (or non-RESTful) as http://geo.com/states/nevada, http://geo.com/states/321, http://geo.com/states?id=321 and http://geo.com/foo-bar-U7q. The URL structure simply doesn't matter in REST.
But from a human point of view it helps understanding if the API has some kind of meaningful URL structure. Computers may easily ignore URL structures but as humans we tend to look at URLs and try to infer meaning from that. Thus, having pretty and well structured URLs helps us understand what is going on - not only as client developers but certainly also as server developers who often have to navigate from URLs to source code - and having a well defined URL structure helps us with that process.
In order to discuss URL structures we need a domain to model. I think geographical information with countries, states and cities should be easily understood by most, so lets try that. I will ignore the fact that many countries doesn't have states ;-)
URLs as identifiers for entities
Our geographical domain easily lends itself to some kind of hierarchical structure of countries / states / cities. So intuitively we reach out for a hierarchical URL structure as shown below (for the sake of clarity I will ignore the host name and only show the path element of the URL). Let us try to build the URL for the city of Las Vegas in Nevada, USA:/countries/USA/states/Nevada/cities/Las+Vegas
That would work, but think a bit about it; what if the state of Nevada had more than one city called Las Vegas? How would we be able to distinguish between the two cities? The problem here is that we confuse searching for a city named Las vegas in Nevada, USA with the concept of identifying a specific city.
I believe that it is fair to assume that most geographical systems will have some kind of backend that assigns unique identifies to all of its entities. This may be integers, GUIDs or strings with composite keys - but in the end it boils down to a sequence of characters that uniquely identifies the entity in the system.
So let us assume that the well known city of Las Vegas is identified by the integer 82137 which is a unique city number. It may happen to be the same number which is used for a country or a state, but in the context of cities it is unique.
The same goes for countries and states: USA has the ID 54 and Nevada is identified by 7334. Now we get the URL:
/countries/54/states/7334/cities/82137
But what happens if some client decided to lookup this URL with mismatching IDs:
/countries/54/states/8112/cities/82137
Well, that should be considered a non existing resource and the server should return HTTP code 404 Not Found.
But why bother at all with the overhead of checking both state, country and city IDs when the city ID uniquely identifies the city? It would be easier for all parties if only the city ID was needed in the URL:
/cities/82137
Now the server can do one single lookup by the ID to see if the referenced city exists. No need for any additional checking for matching state and country.
The same logic can be applied to states (and countries is trivial), so we end up with the following canonical URL structures for countries, states and cities:
/countries/{country-id}
/states/{state-id}
/cities/{city-id}
Should it happen that the server doesn't assign unique IDs to cities (or states), and really needs the state reference for a city, because two cities in different states may have the same (non-unique) ID, then we must include both in the URL:
/states/123/cities/77 => Rome in Italy (assuming some state in Italy is identified by 123)
/states/432/cities/77 => Rome in the state of New York
In the rest of this post I will assume that all cities and states has "globally" unique IDs.
Finding the right ID with UI dropdowns
But how does the client know what ID to use, you may ask? This depends on the application, but lets take the scenario where an end user needs to get information about the city of Las Vegas (while still assuming that Nevada may have two Las Vegas).The UI could be structured by three dropdowns: one for countries, one for states in the selected country and one for cities in the selected state. To present such a UI for the end user we first need to be able to get the list of all countries. The obvious choice for this resource is /countries. Then, for the selected country we need the list of states. The obvious choice here is /countries/{country-id}/states.
But what about the list of all cities for a specific state in a specific country? Let us avoid the trap of a hierarchical URL with multiple IDs and use the short /states/{state-id}/cities.
So now we have the following resources representing lists of geographical items:
/countries
/countries/{country-id}/states
/states/{state-id}/cities
Each of these resources returns a JSON list as shown below and from this list the UI can easily build a dropdown element for selecting a city:
[
{ Name: "Item name A", ID: xxx },
{ Name: "Item name B", ID: yyy }
]
In this way the client gets the unique city ID by letting the end user select a city and its corresponding ID.
Query by text search
Another approach could be to use textual searching where the end user enters a query text like "Las Vegas, USA" (which is how Google maps work). This would require a new query resource:/cities?query=Las+Vegas,+USA
The result would be a list of matching cities:
[
{ Title: "Las Vegas, County A, Nevada, USA", ID: 16352 },
{ Title: "Las Vegas, County B, Nevada, USA", ID: 82137 }
]
Now the end user can select one of the results and thus get the ID of the city.
Adding hyper media, getting closer to REST
The previously mentioned approaches requires the client to create URLs by combining URL templates with IDs. This means the client has to be hard coded with the URL templates - and the consequence is a tight coupling to the URL structure of the web API.But it is very easy to avoid this kind of URL coupling by using hyper media elements in the returned representations. Take for instance the list of cities matching the text "Las Vegas, USA"; here we can include the actual city URLs in the response instead of requiring the clients to construct the URLs itself:
[
{
Title: "Las Vegas, County A, Nevada, USA",
ID: 16352,
CityLink: "http://.../cities/16352"
},
{
Title: "Las Vegas, County B, Nevada, USA",
ID: 82137,
CityLink: "http://.../cities/82137"
}
]
Now we can start talking about a RESTful service instead of a static web API: by including hyper media elements we allow the server to include links to other hosts that might be better to represent cities:
[
{
Title: "Las Vegas, County A, Nevada, USA",
CityLink: "http://other-geo-service/jump.aspx?type=city&ID=16352"
},
{
Title: "Las Vegas, County B, Nevada, USA",
CityLink: "http://geo.com/cities/82137"
}
]
By including links we have stopped worrying about URL structures and has come one step closer to a RESTful service.
The upside is looser coupling to server URL structures, simpler client logic and enabling the use of different services on different servers. The downside is a larger payload with bigger URLs than simple IDs.
Filtering
So far we have looked at hierarchical data with some obvious URL structures. But what if we need to get the list of cities with a population of more than 200000 citizens? And what if we only want cities from the state of Massachusetts?There are many different ways to do this depending on the complexity of the filtering. But it may be fine to start out with simple queries like "All cities in (Massachusetts or New York)"; first we need to use state IDs and thus we get "All cities in states (2321, 2981)". Such simple integer IDs can be separated with commas, so one possible URL structure could be:
/cities?states=2321,2981
It is also possible to encode an SQL like query language in one single parameter:
/cities?where=state+in+(2321,2981)+and+population+greater-than+200000
The possibilities are endless, but it usually consists of a path like /cities that identifies the type of query together with some set of URL parameters encoding the query specification.
A common solution is to interpret "&" as AND and "," as OR when possible. So for instance /cities?states=2321,2981&size=large,huge would mean "All cities where state is either (Massachusetts OR New Your) AND size is either (large OR huge)".
And no discussion about filtering without mentioning OData's URL conventions: http://www.odata.org/documentation/odata-v3-documentation/url-conventions/
Handling large input filters
URLs for filtering may become rather large, so another recurring question is "How do I handle filter strings too large for a URL"? The recommended solution is to POST the filter to a query resource, for instance like this:POST /city-filters
Content-Type: application/x-www-form-urlencoded
where=state+in+(2321,2981)+and+population+greater-than+200000
The server then creates a temporary resource for this query and returns a redirect to it:
201 Created
Location: /city-filters/9638
The client can then GET /city-filters/9638 to get the result of the query.
A nice side effect of this is that the created filter resource can be cached to avoid re-calculating the potentially very slow query on the server.
Natural keys, surrogate keys, URL aliases and resource duplication
A common question relates to the use of natural keys versus surrogate keys in URL construction. It is more or less the same discussion as we see with databases (see for instance http://www.agiledata.org/essays/keys.html). Examples of natural keys could be order numbers, e-mails, postal codes, social security numbers and phone numbers.When choosing between natural keys versus surrogate keys you should consider the lifespan of the key; URLs are supposed to be stable over a very long period of time, so do not choose keys that vary over time. For instance, do not use phone numbers and e-mails to identify people since people tend to change these during their life.
You should also beware of natural keys which can be used by more than one entity. It is for instance (still) common for some members of a family to share a common e-mail, so e-mails are not good candidates for identifying persons. Even social security numbers may sometimes change. In Denmark for instance a person may get a new social security number if they change gender.
A valid natural key could be a sales order number since these are supposed to be both unique and stable.
But if we introduce natural keys, should we then only use natural keys? What if an entity has both a natural key and an internal surrogate key? You can use both but you should decide on one being the canonical ID and avoid duplicating resources by using HTTP redirects for the secondary keys.
Take for instance a sales order with the order number SK324-1 and internal surrogate key 887766 - if we consider the order number as the canonical ID then we can use these URL structures:
/orders/SK324-1 => returns order representation
/orders/id/887766 => redirects to /orders/SK324-1
Redirects should be done using the HTTP status code 303 See Other with a Location header containing the canonical URL.
As stated earlier on: do not confuse searching with identity. You may want to search for a person with a specific e-mail, but the result should include the canonical URL of the found person.
See also http://www.w3.org/TR/webarch/#uri-aliases for a discussion of URL aliases and duplication.
Relations and back-references
What if we want back-references and other relations to other resources, does that influence the URL structure? For instance, now that we have links to states in a country, we might also want links to the country in which a state belongs. That might lead to something like this:/states/{state-id}/country
But, wait a minute, we already have links to countries, right? The canonical version is although /countries/{country-id} so how do we get from /states/{state-id}/country to /countries/{country-id}? The obvious answer is to consider the /states/{state-id}/country URL as an alias for some country and use HTTP redirects to get to the canonical country URL.
But lets step back and take a broader look at relations in general; a back-reference is just one kind of relation from one resource to another - but we could have many other kinds of relations, like "neighbor states", "the country of a city", "statistical information about a state" and so on. The general solution to this concept is to include links in the payloads instead of creating a myriade of small alias resources that only redirects to canonical URLs.
So, instead of using /states/{state-id}/country for the country of a certain state, we include the canonical country link in the representation of the state:
GET /states/4321
returns =>
{
Name: "State X",
CountryLink: "http://.../countries/1234",
NeighborStatesLink: "http://.../states/4321/neighbors"
}
Static data, volatile data and caching
Some times we end up with some sort of "hotspot" resource with tons of requests and a very volatile content making it impossible to cache the result and improve performance in that way. A solution to this may be to split the resource into two (or more) different sub-resources; a cacheable resource and a volatile non-cacheable resource.Take for instance our state resource at /states/{state-id} - it may contain some very static data like the name of the state, its area and such like plus some volatile data like for instance the number of Tweets tweeted from that state the last ten minutes. The static information could easily be cached, but we have no way to do it since the complete resource also contains the number of Tweets.
The solution is straight forward: split the resource into two different resources:
/states/{state-id} => static state information
/states/{state-id}/tweet-stats => volatile tweet information
I'll admit that the above example is rather contrived, so lets try a more realistic example: a streaming music distribution network publishes information about its songs through an online web API. Each song has its own resource representation with details about the song. The title, lyrics, artist and such like won't change much (if ever), but the company also publishes the number of current listeners which changes all the time. To improve caching characteristics the song data is split into (at least) two different resources:
/songs/{song-id} => static song details (cacheable)
/songs/{song-id}/usage => volatile usage information (non cacheable)
But who says the song usage is published by the same API? Some time after the initial release of the web API the company off-load some of the streaming to another content delivery network which will also deliver the usage statistics. Now suddenly not only the URL structure changes but even the host name changes:
/songs/{song-id} => static song details (cacheable)
http://cdn.com/acme/file-usage/{song-id} => volatile usage information (non cacheable)
This is a breaking change and all clients must now be upgraded. Had the API instead contained hyper links then the change would have been transparent to all clients.
Classic song representation:
{
Id: 1234,
Name: "My song"
}
Hyper media improved representation:
{
Id: 1234,
Name: "My song",
UsageLink: "http://cdn.com/acme/file-usage/1234"
}
Once again we see how unimportant the actual URL structure is when we start using hyper media elements in the responses.
Formats and content types
If the same resource can be found in different formats (encoded with different media types) then we can ask ourself, should URLs end on .json .xml or similar extensions? On one side it makes it easy to explore the different representations using a standard web browser - on the other side it introduces different URL aliases for the same resource.My recommendation is to implement the extensions as a convenience for the client developers, but avoid using them when interacting with the API "for real". If for instance our geographical API can return both JSON as well as XML and HTML then I would use these URLs for states:
/states/{state-id} => canonical URL used in all returned hyper media elements
/states/{state-id}.json => JSON representation of state
/states/{state-id}.xml => XML representation of state
/states/{state-id}.html => HTML representation of state
The canonical URL would also support standard HTTP content negotiation for JSON, XML and HTML representations of the exact same resource. The framework I use, OpenRasta, supports this dual type of "content negotiation" right out of the box with no implementation overhead.
If our resources have different variations then we can add them as "sub resources" of the primary resource (not that such a thing really exists since URLs are opaque strings). Where I work we have resources for documents in a case management system. These resources contains meta data about the document (title, owner and so on) - and then we have various other (sub) resources for the documents themselves - the raw binary document (image, power point, pdf etc.), a PDF replica of the document and a PDF replica with an added front page containing the document meta data. Thus we get these URLs:
/documents/{doc-id} => canonical document meta data URL
/documents/{doc-id}/pdf => PDF replica
/documents/{doc-id}/meta-pdf => PDF replica with meta data frontpage
Use NOUNS not VERBS
I think most people get this right nowadays: URLs should be NOUNS not VERBS. Avoid URLs like /getOrders and /updateCountry - use all of the HTTP verbs instead when interacting with the resources and use something like /orders/{order-id} and /countries/{country-id} for the URLs. If you run out of HTTP verbs then invent new resources.In this way you will avoid the trap of doing something horrible like this which I would expect to delete order number 1234 when you GET the resource:
GET /orders/1234/delete
You also get the ability to identify all your resources and add caching, which is not possible with this sort of old school SOAP'ish look-up mechanism:
POST /orders
Body => { OrderId: 1234, Operation: "read" }
And you get a nice explorable and consistent API that you developers will love to use :-)
Versioning
Where should API version numbers go in the URL? Should it be /api/v1/countries, /countries-1 or maybe in the host name http://v1.api.geo.com/countries?Well, API and URL versioning is a whole story in itself so I suggest you take a look at Mark Nottingham's excellent "API versioning smackdown" (http://www.mnot.net/blog/2011/10/25/web_api_versioning_smackdown) for a good discussion on this subject.
Have fun, hack some code and create beautiful APIs out there :-)
/Jørn
Abonner på:
Opslag (Atom)

