I am writing about how to design a REST API. I am basing my guidance from Stormpath’s presentation on July 10th, 2012. A REST API is a type of application programming interface (API) that is exposed as web-like HTTP resources. They provide access to an application’s logic. The goal of REST API design is scalability, independence, security, generalization, low latency, and encapsulation.
JSON Payloads
The first thing to describe is how data is transmitted. Several open protocols have been proposed including WSDL, SOAP, and JSON. The best approach today is to use the simplest approach, which are JSON payloads. JSON originated from JavaScript object notation, but nowadays they have their own standard. JSON is the most likely correct solution because it is simple. Everything in the JSON is a basic data type such as a string, number, object, or array.
JSON payload names should be specified using camel case (lower first character then captialize the first word of each subsequent word) following JavaScript convention.
For nested resources in JSON payloads, JSON entities can have a { “href” : “resource-url” }
value to specify hyperlinks to the child resources. These resources can also be expanded out to reduce roundtrips to the server for related information. Such requests can be passed as parameters to the resource URL.
HTTP Resources
The second consideration is how to provide HTTP resources. . These resources should be designed in such a way that they are discoverable without referring to additional documentation. They should follow the principle of KISS – keep it simple stupid. Resource names should be provided by plural or singular nouns. For example,
/users
/computers
And instances of a resource should be accessed using a numeric or mixed string key, such as,
/users/123
/computers/y3bza4
Verbs, adverbs, and adjectives should not be provided in REST APIs if one is following CRUD – create, read, update, and delete.
HTTP resources also are associated with verbs: GET, PUT, POST, and DELETE. Here is the preferable convention for enabling CRUD operations:
- GET – returns an object. Of these HTTP verbs only GET has no side effects when called multiple times.
- PUT – assigns a specific object a value to a resource instance (e.g., when resource ID is known)
- POST – assigns a specific object value to a “controller” resource, which decides how the resource instance should be created/modified (e.g., when resource ID is unknown or hasn’t been created).
- DELETE – removes an existing instance of a resource
When adding JSON support to an existing API, Accept and Response headers in the HTTP request should specify “application/json”. The return codes from HTTP should follow standard-documented codes. It may also be useful to pass error messages and additional error codes in the JSON response payload.
Advanced REST API Topics
Next time I’ll talk about how to handle resource parameters to paginate resource requests and creating resource instance IDs.