Services-First: A Better Way to Build a Web Application
When you're building a web application, it's a powerful design heuristic to build a REST web service API, and build your application on top of your service.
By Ryan McGreal
Posted February 02, 2012 in Blog (Last Updated February 02, 2012)
Contents
1 Introduction ↑
The best way to find yourself is to lose yourself in the service of others.
-- Mahatma Gandhi
When you're building a web application, it's a powerful design heuristic to develop your functionality as a web service and then build your application on top of your service.
The functionality your application needs to perform should all be accessible or at least exposable as web services. This enforces a responsible design approach that will pay real dividends in maintainability, extendability and reduced technical debt.
It may also pay unexpected dividends in generating value over and above the principal goal of your web application. By thinking about your application design as a web service, you open up the possibility that the real value you deliver is not what you thought your service was going to be, but some subsidiary or extraneous solution you develop that turns out to be a) useful to others and b) scalable/profitable.
1.1 The Infamous Yegge Platform Rant ↑
Last October, Google engineer Steve Yegge posted a long, thoughtful rant on his public Google+ page in which he argued that Google "does everything right" - except platforms, which he argues Google still doesn't really understand. Rather, Google provides products, not services.
Yegge's essay was directed internally at his fellow Googlers, and he took it down after realizing he had accidentally posted it publicly. Luckily for us, copies are still available with Yegge's blessing.
Yegge contrasted his former employer, Amazon, which overwhelmingly adopted a services-first approach after founder and CEO Jeff Bezos ordered every business unit in the company to start exposing its functions to the rest of the company as a web service.
2 Service-Oriented Architecture (SOA) ↑
SOA is a methodology for developing software as a collection of services. Every functional unit exposes its functionality via API calls, and each unit consumes other units' services by accessing those API calls. The services are modular, exposable and 'mashable'.
2.1 Platforms ↑
According to Yegge, Amazon recognized that a services-first approach would enable Amazon to provide a platform on which other companies can build their businesses.
[T]he first big thing Bezos realized is that the infrastructure they'd built for selling and shipping books and sundry could be transformed an excellent repurposable computing platform.
A platform is a system on which others can build applications and products. A product can be used, but a platform can be programmed and extended. Users can create, access, modify and share resources programmatically.
Outside developers can build applications on top of your platform. The more accessible your platform is, the more people will use it and the easier it will be to achieve critical mass and positive network externalities.
Metcalf's Law states: The value of a network is proportional to the square of the number of connected nodes. As the number of people using your platform increases linearly, the overall value can increase geometrically.
2.2 Applications ↑
Applications are programs built on top of platforms that are meant to be used directly.
A good platform is hackable, in the sense that it is general and flexible enough to allow third parties to build applications that the platform designer might never have imagined.
The more powerful, reliable, accessible and flexible a platform is, the more likely it is that someone will build a "killer app" - a program so useful that it makes the platform indispensable. Think of VisiCalc on the Apple II, Lotus 1-2-3 on the PC, or Microsoft Office on Windows.
2.3 Electricity Grid ↑
Here's another platform that attracted killer apps: the electricity grid. When the grid was first built, it was dedicated to powering lights. There weren't even outlets: electrical lines were hard-wired to light bulbs.
But it didn't take long for innovators to recognize that there were lots of other uses for electricity. Within a few years, electric fans, irons and toasters became extremely popular.
The first appliances didn't have plugs: they had connectors that screwed right into light bulbs. When outlets were introduced, they provided a much safer, more flexible user interface for the power grid.
To this day, innovators are still finding new and creative ways to build on the electricity grid. It's a beautiful platform: about as powerful, reliable, general and flexible as it gets.
2.4 Bootstrapping ↑
When you build a robust platform, you make it easier and more attractive for developers to build on it. The more developers you have building on your platform, the more likely it is that one of those developers will build a killer app. More, better and more popular apps, in turn, make your platform more attractive to developers.
It's a virtuous cycle if you can manage to set it in motion.
2.5 Dogfooding. ↑
Yegge stresses the vital importance of building on your own platform:
The Golden Rule of Platforms, "Eat Your Own Dogfood", can be rephrased as "Start with a Platform, and Then Use it for Everything."
When you dogfood your platform, you have a direct interest in improving it, and that improvement makes it more attractive to developers. You also get to see your platform from your customers' perspective, helping you to understand their needs better. Finally, you demonstrate confidence in your own offerings.
Microsoft built an extremely successful software business through religious dogfooding. The original Windows NT team actually developed NT using computers that ran NT - talk about an incentive to build a stable, functional platform!
A word of warning: taken to the extreme, dogfooding leads to Not Invented Here syndrome.
2.6 Products v. Platforms ↑
Products | Platforms |
---|---|
Targeted | Broad |
Differentiated | Integrated |
Fast to Market | Long-term Strategy |
Maximize profit | Maximize Market Share |
The danger of a business model based on a product offering is that a powerful platform can surround and crowd out a product if the platform allows equivalent functionality. Since computers became widespread, the market for typewriters and calculators has collapsed.
In general, an extensible platform will tend to win over a monolithic product. iPhone and Android crowded out Blackberry in large part because they made it easy for third party developers to extend their functionality.
Similarly, a more open platform will tend to win over a more closed platform. As much as iPhone was more open and accessible than BB, Android is still more open and flexible - even to the point that the operating system can be installed on a variety of third party devices. Its market share has shot ahead of the iPhone.
This is the same story that played out in the early 1980s: Microsoft won the PC operating system market mainly because of its cheap, permissive licencing model. They extended this model to Windows and the Win32 API, which was similarly more open than Mac, Amiga and other systems that were actually technically superior but more closed.
In the 1990s, the World Wide Web crowded out and assimilated Compuserve, AOL, The Source, Prodigy, Minitel and other proprietary networks because it was an open standard with a low barrier to entry.
The story of web servers is the same: the LAMP stack (Linux, Apache, MySQL, Perl/PHP) came to dominate web applications against competition from the proprietary IIS/ASP and .NET alternatives.
2.7 Products to Platforms ↑
Remember, however, that the line between products and platforms is fuzzy. Products use standardized, modular components; design/manufacturing/logistic expertise transfers to new products; and products can generalize into platforms.
Amazon and Facebook both transformed themselves from product companies to platform companies. Today, the killer app on Amazon Web Services is Amazon, and the killer app on the Facebook platform is Facebook.
Yegge points out that it might be painful to maintain the discipline to eat your own dogfood and build services-first, but it is far more painful and expensive to turn a monolithic application into a platform after the fact.
If you delay it, it'll be ten times as much work as just doing it correctly up front. You can't cheat. You can't have secret back doors for internal apps to get special priority access, not for ANY reason. You need to solve the hard problems up front.
According to Yegge, Amazon went through the painful exercise of transforming itself from a product company into a platform company because of necessity:
[I]t took an out-of-band force to make Bezos understand the need for a platform. That force was their evaporating margins; he was cornered and had to think of a way out. But all he had was a bunch of engineers and all these computers... if only they could be monetized somehow... you can see how he arrived at AWS, in hindsight.
2.8 Amazon Web Services ↑
Here is how Bezos himself explained the strategy in his latest annual letter to shareholders:
Our technologies are almost exclusively implemented as services: bits of logic that encapsulate the data they operate on and provide hardened interfaces as the only way to access their functionality. This approach reduces side effects and allows services to evolve at their own pace without impacting the other components of the overall system. Service-oriented architecture - or SOA - is the fundamental building abstraction for Amazon technologies.
Amazon launched its first web service - Elastic Compute Cloud (EC2) - in 2006. Since then, it has followed up with a long list of additional services:
- CloudFront - low latency global CDN
- DevPay - accounts receivable service
- DynamoDB and SimpleDB - schemaless nosql key/value store
- ElastiCache - scalable in-memory cache
- Elastic MapReduce - distributed mapreduce processing for huge datasets
- Flexible Payment Service (FPS) - digital payment service
- Mechanical Turk - on-demand human intelligence market
- Relational Database Service (RDS) - relational database
- Simple Email Service (SES) - bulk and transactional email service
- Simple Notification Service (SNS) - send notifications
- Simple Storage Service (S3) - data storage and retrieval
- Route 53 - Domain Name System service
None of these service are central to Amazon's core business, which is selling books and other consumer products directly to consumers. However, they all began life internally as essential peripheral or supporting functions.
Today, the company can sell these web services publicly because Bezos had the foresight to insist that the company conduct its internal affairs via web services.
The company is secretive about how much revenue it earns directly from its suite of web services, but the best estimates are that revenue reached $500 million in 2010 and $750 million in 2011. Web service revenue is expected to reach $1 billion in 2012 and $2.6 billion in 2015. (Update: AWS earned $12 billion in 2016!)
2.9 Platforms Express Value ↑
No matter what you build, you will develop expertise in a number of related, peripheral functions that support your primary product. If you develop your product in a services-first fashion, you allow for the possibility to expose those peripheral functions to third parties.
No initial product idea survives first contact with the market. Every successful business is successful because it was able to adjust - sometimes wildly - its product and business strategy in response to real-world feedback. Startup gurus call this "pivoting", and a founder's ability to pull it off is decisive in the survival of the business.
Pivoting doesn't mean throwing away what you've built and starting over. Rather, it means re-purposing what you've built to reach a more promising market.
Many successful startup products started out as components of larger, less focused products. In his book The Lean Startup, entrepreneur Eric Ries calls this the "zoom-in pivot". Other businesses started out assuming they would be selling to one market and ended up attracting interest from a different sector altogether.
A services-first approach decouples your product from the platform it's built on, allowing you more flexibility to change it as required. It also allows you to provide the platform itself to clients as an additional source of value.
3 Designing Your Web Application ↑
So when building your web application, it's a powerful design heuristic to build a web service first, and then build the application on top of it.
3.1 Why a Heuristic? ↑
Application design is not linear or deterministic, it's open-ended, incremental and adaptive. Small changes early on can push an application in vastly different directions.
Most important, there isn't one right way to do things. Ten different developers given the same problem will create ten different solutions - and any number of them can be 'good enough'.
When you can't reason your way to a proof, you have to fall back on a less certain, more exploratory approach. A heuristic is a method of approaching the problem that tends to help you produce good solutions but falls short of being a solution itself.
Think of a heuristic as a general rule of thumb rather than a specific prescription.
3.2 Design Goals ↑
For the end user, a web service should be:
- Useful - The most elegant web service in the world won't interest anyone if it doesn't solve real problems.
- Usable - Similarly, the most useful web service won't be adopted if people can't figure out how to use it.
- Explorable - The easier it is to navigate and discover what a service does and how to use it, the more it will be adopted.
- Accessible - In the case of a web service, accessibility means a variety of clients can use and interact with it.
- Combinable - The purpose of web APIs is so clients can combine data and functionality from a variety of sources to build new things.
- Flexible - Your own product is not the only thing that can be built with your platform. Your API should be open enough to allow for use cases you couldn't imagine.
For the web service developer, a web service should offer and/or encourage:
- Clean, consistent organization of data and functionality
- Separation of different layers in the application stack
- Flexibility to change the application built on it
- Clarity of abstractions
Finally, the developer is also an end user and will also benefit from usefulness, usability, discoverability and so on.
3.3 Design Considerations ↑
With these goals in mind, I propose the following design considerations. Again, since design is non-deterministic, these considerations can help you to make decisions in the open-ended design process that will tend to point you toward a better final product.
3.3.1 Design for Adoption ↑
The entire purpose of an API is for people to use it. If you're not sure how to design something, use this question as a guide: What will make it easier for users to understand how this works and how to use it?
If you force yourself to be a user, you will be more inclined to look at the API from the user's perspective.
3.3.2 Design for Maintainability ↑
Developers spend more time fixing, refactoring and modifying existing code than they spend creating new code. Your API should be designed in such a way that it is easy to dive in and work with existing code. One way to achieve this is through what the Rails developers call convention over configuration. An architecture that builds on established standards will be easier to maintain.
3.4 Web Service APIs ↑
There are two basic kinds of web service:
- Arbitrary Remote Procedure Calls (RPC)
- Hyper-Text Transfer Protocol (HTTP)
3.4.1 Remote Procedure Calls ↑
RPC is a client/server model that allows a client to execute a remote procedure as if it was a local procedure. It uses HTTP as a dumb transport tunnel, and all the objects, methods and data required to call the procedure are transferred inside the message body.
RPC is arbitrary in that the method of transferring data and methods over HTTP varies from one type to another. A number of competing RPC protocols emerged in the early days of the internet: CORBA, XML-RPC, MS-RPC, and so on.
3.4.2 SOAP ↑
By the end of the 1990s, one format had emerged as a de facto standard: Simple Object Access Protocol (SOAP), which was a formal attempt to standardize XML-RPC.
A SOAP web service, all methods are accessed via a single endpoint URL. Methods and data are transferred inside an XML payload, and all requests use the HTTP POST method.
The functionality in a SOAP web service is defined in a Web Services Description List (WSDL).
3.4.3 SOAP Benefits ↑
SOAP was an improvement over previous RPC approaches. Because it was more or less standardized, it allowed for push-button tooling and deployment. The WSDL allowed properly configured clients to introspect the web service's functionality and abstract away the "web" part of the transaction.
3.4.4 SOAP Problems ↑
However, these benefits are not unalloyed. The XML payloads are extremely verbose and not very human-readable. The standards are arbitrary, poorly defined and have changed more or less constantly for over a decade.
Worse, the system is designed to be interoperable, but a client in, say, C# often cannot consume a WSDL built in Java. At bottom, SOAP is a leaky abstraction that promises easy tooling and wide accessibility but often fails to deliver.
But the worst problem with SOAP is that it re-invents the functionality of HTTP on top of HTTP. It tunnels through the web, but does not work like the web.
4 Hyper-Text Transfer Protocol (HTTP) ↑
Often called "Representational State Transfer" (REST), an HTTP web service is a client/server model that works like the web. The client makes an HTTP request to the server, and the server sends a response back to the client.
HTTP web services are stateless: each request contains all the information needed to process it. HTTP web services are also cacheable and can define rules around which responses can be stored locally or in an intermediate server.
The concept was formalized in 2000 by Roy Fielding, one of the architects of Hypertext Transfer Protocol (HTTP), in his doctoral dissertation. It is not surprising, then, that REST and HTTP mesh very smoothly.
A RESTful client-server system is stateless, meaning each request against the server contains all the information the server needs to process it; and cacheable, in that the server can specify whether and for how long resource representations can be cached either locally on the client or on intermediate servers between the client and the server.
4.1 HTTP ↑
Hypertext Transfer Protocol (HTTP) is a stateless protocol based on a client requesting a resource across a network and the server providing a response. As such, an HTTP transaction entails a request and a response. The request goes from the client to the server, and the response goes from the server back to the client.
4.2 HTTP Requests and Responses ↑
In HTTP, the client makes an HTTP request to the server and the server issues an HTTP response.
4.2.1 Requests ↑
An HTTP request has three parts:
The request line, which includes the HTTP method, the URL and the HTTP version:
GET /users/1 HTTP/1.1
One or more optional HTTP headers, which are key/value pairs with metadata about the data being requested and/or provided.
An optional message body, which is data being sent from the client to the server as part of the request. E.g. in a POST request, the message body will include the data that the server should use to create a new resource.
4.2.2 Response ↑
An HTTP response also has three parts:
The HTTP Status Code, which indicates the status of the requested resource:
HTTP/1.1 200 OK
One or more optional HTTP headers, which are key/value pairs with metadata about the response being provided.
An optional message body, which is a representation of the resource that was requested (hence the name "Representational State Transfer").
4.3 URLs and Resources ↑
In a RESTful architecture, each URL represents a resource. This is vitally important: a resource is a noun, an object, and not the action performed on it.
A RESTful web service has multiple endpoints - one for each resource. (Contrast SOAP, which has only one endpoint and puts everything else - objects, methods, parameters, etc. - into the XML payload.)
If you find yourself creating URLs like /create_user
, you're doing it wrong. Instead, create a URL like /users
and map your user object to that URL.
Remember: a resource is a noun, not a verb.
4.4 HTTP Methods ↑
If a resource is a noun, the HTTP Method is the verb. What you do to the resource with your request depends on what method you use. If a URL is an object, the HTTP method is the action you execute on that object.
Method | Action |
---|---|
GET | Retrieve a resource |
POST | Create a new resource |
PUT | Update an existing resource |
DELETE | Delete an existing resource |
In our user example, execute an HTTP POST request on /users
to create a new user. The server should respond with the specific URL of the user you created: /users/1
.
To view a representation of that resource, issue an HTTP GET request on the user's URL: /users/1
.
To update the user, issue an HTTP PUT request on the user's URL with the new user data in the request body.
To delete the user, issue an HTTP DELETE request on the user's URL.
4.4.1 GET Method ↑
To retrieve a resource, issue an HTTP GET request. GET requests are idempotent (see below), which means making a GET request multiple times does not cause any change in the resource that is requested.
GET requests do not include a message body, but GET responses usually do.
4.4.2 POST Method ↑
To submit data to be processed, issue an HTTP POST request. POST requests require a message body, i.e. the data to be processed.
For example, if there is a resource called /articles
and you want to add a new article, issue a POST request to /articles
with the content. The server should create a new subsidiary URI under /articles
- for example, /articles/1
- and assign that URL to the content you sent with your POST request.
Important note: POST requests are not idempotent, meaning multiple POST requests will create multiple resources with unique identifiers.
4.4.3 PUT Method ↑
To update the resource at an existing URL, issue an HTTP PUT request on that URL. For example, if there is a URL /articles/1
and you want to replace the content served at that URL, issue a PUT request to that URL with the new content.
Important note: PUT requests are idempotent, so issuing 2 or 5 or 50 identical PUT requests will have the same effect on the resource as issuing just one PUT request. Like POST requests, PUT requests include a message body (the resource to be placed at the URL).
4.4.4 DELETE Method ↑
To remove a resource (and remove its accompanying URL), issue an HTTP DELETE request. DELETE requests should be idempotent, i.e. issuing 1 or 2 or 5 or 50 identical DELETE requests will delete exactly one resource. DELETE requests do not require a message body.
4.5 Idempotence ↑
This funny-looking word is really important: a request is idempotent if making it multiple times has the same effect as making it just once. Read that again if you have to.
A request is not idempotent if issuing it more than once has a different effect than issuing it once.
For example, a POST request to add a comment to a document is not idempotent: issuing the POST request twice adds the comment twice, so that the document contains two comments with unique URLs.
However, a PUT request to update an existing comment is idempotent: whether you execute the request once, twice or twenty times, the result will be exactly the same.
4.6 HTTP Headers ↑
Both HTTP requests and responses can include optional HTTP Headers, or key/value pairs that supply meta-data about the request and the response.
4.6.1 Accept Header ↑
An HTTP request can include an Accept
header that specifies what media types the client will accept in a response.
In a REST web service, the request should include an Accept
header with the preferred media type - e.g. application/json
- and the server should attempt to fulfill the client's preference in its response, given its capabilities.
If you are willing or required support multiple formats (e.g. JSON, XML, YAML), the best way for the client to specify what format they prefer is via the Accept
header.
Here are some examples of Accept headers:
JSON:
Accept: application/json
XML:
Accept: application/xml
YAML:
Accept: application/x-yaml
Note: YAML has an x-
prefix because it is not a formalized MIME type. For thoroughness, you could accept all four possibilities:
application/x-yaml, application/yaml, text/x-yaml, text/yaml
4.7 HTTP Status Codes ↑
HTTP has a great way of telling the client whether the request was successful or an error has occurred: HTTP status codes. Every HTTP response includes a status
header with an HTTP status code that indicates the status of the request.
This tells the client whether the request was successful or not, and what to expect by way of a response. It's important to send the right status code.
401 Unauthorized (Image Source: Flickr)
I also include HTTP status codes and error descriptions in the response body. A REST purist might call this overkill, but remember that you want to make your API as self-documenting and easy to use as possible.
For the purposes of your web service, there are three categories of HTTP status codes you need to worry about: success codes, client error codes, and server error codes.
4.7.1 Success Codes ↑
HTTP success status codes provide useful information about successful requests:
- 200 OK - A GET request was successful at retrieving a resource.
- 201 Created - A POST request was successful at creating a resource.
- 202 Accepted - This means the request was accepted but the response is not ready. Useful for queued or otherwise deferred processes.
4.7.2 Client Error Codes ↑
- 400 Bad Request - The request data could not be parsed properly, or a value was missing or invalid.
- 401 Unauthorized - The user requested an access-restricted resource but authentication either failed or was not provided.
- 404 Not Found - The user tried to request a resource that does not exist.
- 405 Method Not Allowed - User tried to execute an HTTP method on a resource that does not allow it. E.g. a POST request against
/users/charlie
instead of/users
. - 406 Not Acceptable - The request came with an
Accept
header for a media type that the server cannot provide in the response. - 410 Gone - A previously available resource has been removed permanently.
- 429 Too Many Requests - Useful if you've rate-limited your API for a given user.
4.7.3 Server Error Codes ↑
- 500 Internal Server Error - Try to avoid this one. It generally means your web service is broken.
- 501 Not Implemented - User has tried to send a request method that your server doesn't recognize.
- 503 Service Unavailable - This tells the client the service disruption is temporary.
4.8 Media Types ↑
In an industry known for bad acronyms, this may be the worst: Hypertext As The Engine Of Application State (HATEOAS) is a mandatory requirement for a web service to meet Roy Fielding's criteria of a "RESTful" design.
Here's how Fielding explained it in a blog post that took issue with the profusion of web services that called themselves "RESTful" but clearly weren't:
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
There, isn't that clear?
In short, Fielding's requirement is that a client should not need any out-of-band information to be able to access, navigate, use and execute a web service. All it should need to know are the base URL endpoint and the media type (identified as the Content-Type
header in the response) of the web service so it knows how to interpret the responses.
In other words, if your web service has a custom way of identifying hypertext URLs in its responses, your web service must also have a dedicated media type that corresponds to how your service works and includes a description of how it works.
In other words, if the client has to read your documentation to discover how your web service works, it is not RESTful because it depends on out-of-band information (i.e. the documentation); but if your web service has a custom media type and the client needs only to read a bunch of documentation to understand how your media type works, it is RESTful because it doesn't depend on out-of-band information.
5 Designing a RESTful Web Service ↑
5.1 Don't Reinvent the Wheel ↑
HTTP was invented to allow clients to request resources from servers across the internet and for those servers to respond with representations of those resources. The entire internet runs on it. It's flexible, powerful and offers a clean abstraction model based on resources and methods.
Don't re-implement what HTTP does in an ad-hoc way on top of HTTP. Just use HTTP.
Many web services only use HTTP as a network tunneling protocol, and then pass objects, methods and parameters inside an 'envelope' that contains all the information. This type of web service architecture includes SOAP and other Remote Procedure Call (RPC) formats.
Web services that actually use HTTP the way it was designed are called Representative State Transfer (REST) web services. Unfortunately, REST is widely misunderstood and a lot of web services that call themselves "RESTful" aren't.
5.2 Discoverable API ↑
In a RESTful web service, a GET request on a base API URL returns a list of resources available in the API. Critically, each resource has a direct URL. This makes it very easy for developers to step into your API and figure out what is available.
Now, you may be thinking you've seen this pattern before. You're right: it's exactly how every single website works. Go to the homepage, and what do you find? Links to the other resources on the website!
A RESTful approach makes your URLs hackable. If your API user is looking at a URL like: /cats/miss_mew
, they should be able to lop off the /miss_mew
and do a GET request against /cats
to return the base collection of cats (each with its own URL, of course).
5.3 REST Resource/Method Matrix ↑
At a conceptual level, a RESTful web service API is a matrix of resources and methods that exposes the functionality of the service to third party applications. Below is an example of what that matrix might look like.
Again, I will repeat that actions are not mapped to URLs. A resource is an object - a noun - and the action inheres to the HTTP method - a verb - not to the URL.
As a result, the same resource URL can serve different responses (corresponding with different actions) depending on the HTTP method used.
Request | Response | Idempotent | |||||
---|---|---|---|---|---|---|---|
Resource | URL | Method | Request Data | Server Action | Response Body | Status Code | |
Users | /users | GET | retrieves list of users | list of users and associated URLs | 200 OK | Yes | |
Users | /users | POST | user details | creates a new user | new URL and user representation | 201 Created | No |
User 9001 | /users/9001 | GET | retrieves details for user 9001 | user representation | 200 OK | Yes | |
User 9001 | /users/9001 | PUT | new user details | updates user details | updated user representation | 200 OK | Yes |
User 9001 | /users/9001 | DELETE | deletes user 9001 | returns status | 200 OK | Yes | |
User 9001 | /users/9001 | GET | checks that user 9001 does not exist | Not found error message | 404 Not Found | Yes |
5.4 Use JSON ↑
JavaScript Object Notation (JSON) is a data serialization format that delivers an optimal combination of the following criteria:
- Lightweight - less boilerplate means less data transfered across the network
- Readable - Humans can easily see and understand the content of a JSON object
- Flexible - allows various nestable data types: object (dictionary), array (ordered list), string, integer, float, boolean
- Interoperable - every programming language and framework under the sun can generate and consume JSON.
- Convertable - JSON can be converted into a native object more easily than XML.
Here's an example of a response to an API base URL GET request, represented in JSON:
{
"ok": true,
"status_code": 200,
"resources": [
{
"url": "/authors",
"resource": "authors"
},
{
"url": "/articles",
"resource": "articles"
},
{
"url": "/blogs",
"resource": "blogs"
},
{
"url": "/comments",
"resource": "comments"
},
{
"url": "/events",
"resource": "events"
}
]
}
Unless you've got a compelling business or technical reason for using a different media type, stick with JSON.
Just remember: if you want to satisfy HATEOAS, you need to give your web service a dedicated media type, e.g.:
application/vnd.my-ad-hoc-web-service+json
Note that the vnd
prefix refers to a vendor-specific media type, e.g. application/vnd.google-earth.kml+xml
for Google Earth KML files.
5.5 Search ↑
Since grammatically, "search" can be a noun as well as a verb, it's okay to have a URL called /search
. Arguably, the best way to filter the response a server delivers to a GET request on /search
is to use a querystring:
/search?doctype=article&keyword=hello%20world
It is possible to do this without a querystring - something like:
/search/doctype/article/keyword/hello%20world
But that's silly and pedantic - and arguably wrong, anyway. It's harder for your users to guess and it's harder for you to parse.
5.6 Pagination ↑
When your user does a GET request on /api/cats
, do they really want a list of 7 million cats? Do you really want to have to serve that and support the processing and bandwidth involved?
Again, I don't think there's anything wrong with using querystrings here:
/api/cats?offset=101&limit=50
Similarly, I don't think there's anything wrong with using terminology that is familiar to developers who work with databases.
5.7 Versioning ↑
Your API is a contract you have made with your users. If you plan to introduce a change to your API that breaks backwards compatibility, you need to do so in such a way that it doesn't break existing clients.
There is no easy, obvious way to do this that will make everyone happy, satisfy REST and satisfy the goal of making your API usable and discoverable.
There are a few different ways you can version your API, all of which have pros and cons.
5.7.1 Versioning in URL ↑
Many popular web APIs do this: /api/v1/cats
. If you roll out a version 2 of your API that would break clients using version 1, you expose it at api/v2/cats
.
- Pro: it's easy for users to understand and doesn't break existing clients.
- Con: results in multiple URLs for the same resource; locks versioning into the URL; multiplies API maintenance issues.
5.7.2 Versioning in Querystring ↑
Some APIs do this: api/cats?v=1
.
- Pro: default URL doesn't need to include version (defaults to newest version); one URL for each resource.
- Con: clients that don't explicitly specify a version will break when the API is updated.
5.7.3 Versioning in Accept header ↑
REST purists recommend putting the version in a custom Accept header: Accept: application/vnd.company.app-v1+json
- Pro: default URL doesn't need to include version; one URL for each resource; changes do not break clients; version is a formatting issue so it's the "right" place.
- Con: more esoteric and difficult for developers to discover how it works.
5.8 Use Secure HTTP ↑
I don't want to say too much about security (though I do recommend the REST Security Cheat Sheet - Draft document from the Open Web Application Security Project (OWASP) as a handy reference), but I will say a quick word in support of Secure HTTP - or HTTPS - rather than plaintext HTTP.
HTTPS is a bit slower, but on a web service, you're not making multiple requests to pull down javascripts, CSS, image files and so on, so you can afford to take a small hit for an encrypted connection.
The payback in client security is worth it.
5.9 Summary of Benefits ↑
It's extremely easy to lose yourself in theory and get sucked into the purity movement (remember XHTML?). If REST doesn't deliver practical results, it doesn't matter how elegant, pure or canonical it claims to be.
In short, a REST API is discoverable and navigable. With no background knowledge, a client can do a GET request on the root URL to get a list of resources with URLS. It's easy to dive right in and quickly figure out what is available.
Even if you don't want to get bogged down in the intricacies of HATEOAS, you will still realize many - indeed, most - of the benefits of this approach if you adopt a RESTish rather than a purely RESTful platform design.
5.9.1 Better URLs ↑
Stable, persistent URLs allow for resource bookmarking and better search indexing.
Sane, well-named URLs are more descriptive than arcane or arbitrarily named URLs.
Hackable URLs allow for better resource discovery.
5.9.2 Developers Understand HTTP ↑
REST is essentially just HTTP, and we already understand HTTP (with an important caveat, below).
The API developer doesn't need to waste time and energy (badly) reinventing/re-implementing what HTTP does on top of HTTP.
The client doesn't need to waste time and energy learning a bunch of ad hoc RPC protocols.
5.9.3 Our Tools Understand HTTP ↑
Just about every programming language can natively perform an HTTP request and parse the response (with an important caveat, below).
6 Problems with REST ↑
REST comes with its own issues, of course, and it would be disingenuous to gloss over them.
6.1 Requires Proper Understanding of HTTP ↑
Much as I wrote earlier that REST is just HTTP and we all understand HTTP, the honest fact is that we don't understand HTTP all that well.
It's true we've all been using it for 20 years now, but for various historical, cultural and educational reasons, there's a constant tension between understanding and using our protocols the way they were designed and knowing just enough to build something that gets the job done.
That latter imperative lowers the barrier to entry into web development, but it also leads to the same avoidable mistakes being made over and over again in applications that require a more professional approach: SQL injection, XSS, hacked cleartext passwords, and so on.
We've all heard horror stories about web applications that didn't understand HTTP and blew up when a search engine bot innocently crawled a GET request to /delete_user.php?username=Ryan
and thereby wiped out the entire database.
For a newbie developer who doesn't really understand HTTP very well, a web service with URLs like /api/create_user
is more immediately obvious than a web service with URLs like /api/users
that require a POST request to create a user.
However, this is changing as the benefits of REST become more widely known and more developers start to take advantage of its defining characteristics.
One thing is for certain: once you've developed and built on a REST web service, you'll finally understand HTTP inside and out.
6.2 Tooling ↑
SOAP advocates argue that mature tooling makes it easy for a service provider to deploy a WSDL and for clients to consume it and execute web service methods as if they were local function calls.
Of course, the reality is less rosy: leaky abstractions, incompatible data types, lack of interoperability between, say, a Java WSDL and a C# SOAP client, and so on.
In far too many cases, I've had to hand-roll an ad-hoc SOAP client and build my own XML templates when a supposedly push-button WSDL turned out to be platform-dependent. Instead of saving time by consuming a WSDL, I was stuck painstakingly reverse-engineering the RPC formatting details that the interface tried unsuccessfully to hide.
Still, SOAP has that enterprise-friendly turnkey appeal, even if the delivery doesn't fulfill the promise.
REST, on the other hand, is sorely lacking in push-button tooling - on both the framework development and client side.
Even tools that ought to know better tend to abstract away the HTTP methods from the developer and generically treat every request as a GET request - unless it comes with form data or hits a kludgy /process_form
kind of an URL.
We've come a long way from the cgi-bin
form processing scripts of the '90s, but we still have a way to go. The good news is that this changing as developers come to recognize the benefits that come from understanding and using HTTP the way it was designed.
6.2.1 Frameworks ↑
Most web application frameworks weren't developed with HTTP in mind, but rather with the minimal subset of HTTP that that is comprised of viewing web pages and filling out forms. Data transfer and processing, even in web applications designed for human users, tends unconsciously to follow an RPC model.
There are already a few that have embraced the full functionality of HTTP more deeply.
I'm not that familiar with Ruby, but I understand Rails 3 is designed to work RESTfully right out of the box with its routing DSL.
Similarly, the lightweight Sinatra framework understands resources and methods natively and simply:
require 'sinatra'
get '/users' do
# show users
end
get '/users/1337' do
# show a user
end
post '/users' do
# create a user
end
put '/users/1337' do
# update a user
end
delete '/users/1337' do
# delete a user
end
In Python, Django is not RESTful by design has some good REST plugins.
The lightweight Python framework I use, web.py, is REST-friendly at its core: resources map to classes and HTTP methods map to class methods.
import web
app = web.application(urls, globals())
urls = ('/users/(.*)', 'User')
class User(object):
def GET(self, name):
# get a resource
def POST(self, name):
# create a resource
def PUT(self, name):
# update a resource
def DELETE(self, name):
# delete a resource
In PHP, you've got Zend_REST, Recess, Tonic and others that understand and support RESTful API design.
The .Net framework has Windows Communications Foundation (WCF). Java has Play RESTlet, Jersey and so on.
6.2.2 Client Tools ↑
Nearly every language understands HTTP, but too many default HTTP modules understand HTTP in a crippled, semi-literate way that reflects how most browsers use HTTP: fetch pages or fill out forms.
In Python, there are no less than three HTTP libraries that ship with the language: urllib
, urllib2
and httplib
- and none of them make the full expressiveness of HTTP particularly accessible.
Fortunately, third party developers have stepped in with libraries like httplib2 and requests, which do a much better job of exposing all the HTTP methods in a sane, consistent manner.
Similarly, REST-aware clients are appearing in other languages as well.
If you're a .net shop, you've got tools like RestSharp.
Of course, JavaScript understands HTTP natively, perhaps better than some other, more "mature" and "full-featured" languages - possibly because JavaScript lives in browsers and breathes HTTP.
var xmlhttp=new XMLHttpRequest();
// GET request
xmlhttp.open("GET", "/users", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert('GET request successful');
// response is in xmlhttp.responseText
}
}
// POST request
var jsonObject = {"username": "ryan", "fullName": "Ryan McGreal"};
var jsonString = JSON.stringify(jsonObject);
xmlhttp.open("POST", "/users", true);
xmlhttp.setRequestHeader("Content-Type","application/json");
xmlhttp.send(jsonString);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert('POST request successful');
// response is in xmlhttp.responseText
}
}
// PUT request
var jsonObject = {"username": "ryan", "fullName": "Ryan G. McGreal"};
var jsonString = JSON.stringify(jsonObject);
xmlhttp.open("PUT", "/users/ryan", true);
xmlhttp.setRequestHeader("Content-Type","application/json");
xmlhttp.send(jsonString);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert('PUT request successful');
// response is in xmlhttp.responseText
}
}
// DELETE request
xmlhttp.open("DELETE", "/users/ryan", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert('DELETE request successful');
// response is in xmlhttp.responseText
}
}
JavaScript also has a panoply of frameworks and libraries that make HTTP requests even easier:
// yay jQuery!
$.get("/users", function(response){ alert('GET request successful'); });
$.post("/users", data, function(response){ alert('POST request successful'); });
$.put("/users/ryan", data, function(response){ alert('PUT request successful'); });
$.delete("/users/ryan", function(response){ alert('PUT request successful'); });
So the tools for creating and consuming REST web services are steadily improving, while the tools for creating and consuming SOAP web services are over-engineered and IMHO over-rated.
In the meantime, REST makes up in discoverability and navigability what it lacks in automated tooling.
6.2.3 Browsers ↑
Of all our tools for working with HTTP, the most universal is the browser. It's the easiest way to browse a web service API, particularly if it works like the web itself. After all, the URL is just a resource on a server accessible via HTTP, and browsers are specifically designed to make HTTP requests and present the responses to users.
However, like other established HTTP-based tools, most browsers are only good at GET and POST requests, not PUT or DELETE requests. Even then, POST requests generally require an HTML form that the user can fill in and submit.
In addition, most browsers are not good at rendering representations in formats other than HTML or XML.
I use Firefox as my main browser (yes, I'm old-fashioned), and I've discovered a few add-ons that make exploring web APIs a lot easier:
- HttpFox - an HTTP analyzer.
- JSONView - pretty-prints JSON response objects in the browser window.
- Modify Headers - Add, modify and filter the HTTP request headers sent to a web server.
- RESTClient - Visit and test REST/WebDav services.
6.3 REST is a Spectrum ↑
Ultimately, it makes sense to talk about an API being more or less RESTful and you probably shouldn't kill yourself to reach 100.00000%.
Like anything else, REST purity is subject to diminishing returns. If you get the important stuff correct - URLs are resources, methods are actions, representations include URLs - you'll get to enjoy the main benefits of a REST design approach without tearing your hair out.
For each choice, ask yourself whether the benefit of going more RESTful justifies the cost. Keep in mind that your goal is to make your API as usable and discoverable as possible.
7 References ↑
Classification of HTTP-based APIs
http://nordsc.com/ext/classification_of_http_based_apis.html
Richardson Maturity Model - A model (developed by Leonard Richardson) that breaks down the principal elements of a REST approach into three steps. These introduce resources, http verbs, and hypermedia controls.
http://martinfowler.com/articles/richardsonMaturityModel.html
REST APIs must be hypertext-driven - Roy Fielding's attempt to get people to understand what he was talking about when he defined REST.
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
RESTful API Design - Pragmatic REST - Webinar by Apigee.
REST Security Cheat Sheet - Draft document from the Open Web Application Security Project (OWASP)
RESTful Web Services: The Basics - IBM developerWorks article
https://www.ibm.com/developerworks/webservices/library/ws-restful/
General Principles for Good URI Design - StackOverflow answer
8 Video ↑
Here is a video of my talk at Hamilton DemoCamp #5.