Notes on RESTful APIs (Updated)
HTTP and REST are not new, we just misused them for a long time. A proper RESTful API should consider the following principles.
Resources are discrete entities - like entities from the Entity-Relationship Model. The web is modeled around resources. Everything is a resource, not a web page, not an application. Resource names should be intuitive and should be nouns. Avoid Verbs in URLs.
represents a collection of items
represents an individual item
Resources can be nested in order to reflect the relationship between them.
In order to filter, order, limit or offset resource entries we should not create separate sub-resources. Here’s where querystring parameters come into play.
HTTP Methods (Verbs)
The HTTP Verbs operate on resources. Resources can be queried and altered using Verbs. Some operations are idempotent.
read item / collection of items
nullipotent – does not modify state, no side effects
create new item alters state each time it is called
idempotent – calling it multiple times has the same effect as the first time
partially update item
display allowed verbs on a resource
How verbs operate on resources
GET collection of items
POST create new item
PUT update collection of items – this is rarely used since it updates the whole collection
DELETE collection of items
OPTIONS could display a quick help on how to query the resource
POST - using POST to create an item at an unexisting resource id is a nono
PUT (sometimes POST) update item
Give a proper response after each request. Applications can be much easier to develop if they get meaningful response codes.
respond 200 ‘OK’ (default)
body with item
after POST (create)
respond 201 ‘Created’
location: /resource/id of created item
body with created item
after PUT/POST (update)
respond 200 ‘OK’
body with updated item
respond 204 ‘No Content’
after a bad request/unallowed method
respond 400 ‘Bad Request’
after encountering a problem on the server side, like a failed SQL query
respond 500 ‘Internal Server Error’
- Self describing API
Each response should provide links to explore the API.
Just like HTML connects multiple pages through links, API responses should have links to other resources.
Ideally, an API could be explored entirely without prior knowledge of its resources, just by knowing its base URL.
Using HTTP headers
Accept: application/json, text/plain
Extension in the URL
Not RESTful, URLs are not the place for Content-Type
Version in the URL /v2/resource Create separate resources for a new version of the API.
Version media types
- Using HTTP headers
Some responses can be cached.
Industry standard. Used by most services.
Part of the HTTP standard. Digest auth uses hashing and a nonce.
Can be used for login similar to classic web applications.