REST API Design Rulebook
URI Format(RFC 3986)
|
|
URI Rules
-
A forward-slash separator (/) must be used to indicate hierarchical relationships
1
http://api.canvas.restapi.org/shapes/polygons/quadrilaterals/squares
-
The URI should not have a slash (/) at the end
1 2
Incorrect: http://api.canvas.restapi.org/shapes/ Correct: http://api.canvas.restapi.org/shapes
-
Hyphens (-) should be used to improve URI readability
1
http://api.example.restapi.org/blogs/mark-masse/entries/this-is-my-first-post
-
Underscores (_) should not be used in URIs
-
In the URI path, lowercase letters should be preferred
1 2 3
1: http://api.example.restapi.org/my-folder/my-doc Correct 2: HTTP://API.EXAMPLE.RESTAPI.ORG/my-fplder/my-doc Correct 3: httpL//api.example.restapi.org/My-Folder/my-doc Incorrect
-
The file extension should not be included in the URI
1 2
Incorrect: http://api.college.restapi.org/students/3248234/transcripts/2005/fall.json Correct: http://api.college.restapi.org/students/3248234/transcripts/2005/fall
-
For the API, a consistent subdomain should be used, and a subdomain named api should be added to the full domain of the API
1 2
Incorrect: http://soccer.restapi.org Correct: http://api.soccer.restapi.org
-
For client developers, a consistent subdomain should be used
1
httpL//developer.soccer.restapi.org
-
URIs that represent document resources should use singular nouns
1
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players/claudio
-
The URI that identifies a collection should use a plural noun
1
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players
-
The URI identifying the resource store should use a plural noun
1
http://api.music.restapi.org/artists/mikemassedotcom/playlists
-
Verb or verb phrase applied to controller name
1 2 3 4
http://api.college.restapi.org/students/morgan/register http://api.example.restapi.org/lists/4324/dedupe http://api.ognom.restapi.org/dbs/reindex http://api.build.restapi.org/qa/nightly/runTestSuite
-
Variable path segments can be used for substitution based on the value of the identifier
1 2
http://api.soccer.restapi.org/leagues/{leagueId}/teams/{teamsId}/players/{playerId} http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players/21
-
CRUD function names should not be used in URIs
1 2 3 4 5 6 7
Incorrect: GET /deleteUser?id=1234 GET /deleteUsers/1234 DELETE /deleteUser/1234 POST /users/1234/delete Correct: DELETE /users/1234
-
A query component of a URI can be used to filter collections or store
1 2
GET /users GET /users?role=admin
-
The query component of the URI should be used for paging to collect or store results
1
GET /users?pageSize=25&&pageStartIndex=50
Request Methods(RFC2616)
|
|
GET is to retrieve a representation of a resource’s state.
HEAD is used to retrieve the metadata associated with the resource’s state.
PUT should be used to add a new resource to a store or update a resource.
DELETE removes a resource from its parent.
POST should be used to create a new resource within a collection and execute controllers.
Request Method Rules
-
GET and POST cannot be used for other request methods
-
Must use GET to retrieve the expression of the resource
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
$ curl -v http://api.example.restapi.org/greeting > GET /greeting HTTP/1.1 > User-Agent: curl/7.20.1 > Host: api.example.restapi.org > Accept: *.* < HTTP/1.1 200 OK < Date: Sat, 20 Aug 2011 16:02:40 GMT < Server: Apache < Expires: Sat, 20 Aug 2011 16:06:40 GMT < Cache-Control: max-age=60, must-revalidate < ETag: text/html:hello world < Last-Modified: Sat, 20 Aug 2011 16:02:17 GMT < Vary: Accept-Encoding < Content-Type: text/html <!doctype html><head><meta charset="utf-8"><title>Greeting</title></head> <body><div id="greeting">Hello World!</div></body></html>
-
HEAD is applied to retrieve response headers
1 2 3 4 5 6 7 8 9 10 11
$curl --head http://api.example.restapi.org/greeting HTTP/1.1 200 OK Date: Sat, 20 Aug 2011 16:02:40 GMT Server: Apache Expires: Sat, 20 Aug 2011 16:03:40 GMT Cache-Control: max-age=60, must-revalidate ETag: text/html:hello world Last-Modified: Sat, 20 Aug 2011 16:02:17 GMT Vary: Accept-Encoding Context-Type: text/html
-
PUT must be used to insert and update the stored resources
1
PUT /accounts/4ef2d5d0-cb7e-11e0-9572-0800200c9a66/buckets/objects/4321
-
PUT must be used to update variable resources
-
Must use POST to create a new resource in a collection
1 2 3
POST /leagues/seattle/teams/trebuchet/players # Note the request message may contain a representation that suggests the initial state of the player to be created.
-
POST must be used to execute the controller
1
POST /alerts/245743/resend
-
DELETE must be used to delete the resource
1
DELETE /accounts/4ef2d5d0-cb7e-11e0-9572-080020c9a66/buckets/objects/4321
-
OPTIONS should be used to retrieve metadata describing the interactions available to the resource
Response Status Codes
Category | Description |
---|---|
1xx: Informational | Communicates transfer protocol-level information. |
2xx: Success | Indicates that the client’s request was accepted successfully. |
3xx: Redirection | Indicates that the client must take some additional action in order to complete their request. |
4xx: Client Error | This category of error status codes points the finger at clients. |
5xx: Server Error | The server takes responsibility for these error status codes |
Response Status Code Rules
- 200 OK (indicates non-specific success)
- 200 OK (cannot be used to communicate errors in the corresponding body)
- 201 Created (indicates that the resource was created successfully)
- 202 Accepted (must be used to indicate that an asynchronous operation has been successfully started)
- 204 No Content (Use 204 if the corresponding body is intentionally empty)
- 301 Moved Permanently (used to relocate the resource)
- 302 Found (this rule should not be used)
- 303 See Other (applied to refer clients to a different URI)
- 304 Not Modified (applied to reserve bandwidth)
- 307 Temporary Redirect (tells the client to resubmit the request to another URI)
- 400 Bad Request (indicates a non-specific failure)
- 401 Unauthorized (must be used when there is a problem with the client’s credentials)
- 403 Forbidden (user access to the resource exceeds permissions, access is prohibited)
- 404 Not Found (404 must be used when the URI cannot be mapped to a resource)
- 405 Method Not Allowed (when HTTP methods are not supported, 405 must be used)
- 406 Not Acceptable (406 must be used when the requested file type cannot be provided)
- 409 Conflict (when attempting to place a resource in an impossible or inconsistent state)
- 412 Precondition Failed (precondition in request header not met, returned 412 and did not execute request)
- 415 Unsupported Media Type (415 must be used when the file type requested by the client cannot be handled)
- 500 Internal Server Error (used to indicate API failure)
HTTP Headers Rules
- Content-Type must be used
- Content-Length should be used
- Last-Modified should be used in the response
- ETag should be used in the response
- Storage must support conditional PUT requests
- Location must be used to specify the URI of the newly created resource
- Cache-Control, Expires and Date request headers should be used to encourage caching
- Cache-Control, Expires, and Pragma response headers can be used to block caching
- Caching should be encouraged
- Expiration caching cache headers should be used with the 200 (OK) response
- Expiration caching cache headers can optionally be used with 3xx and 4xx responses
- custom HTTP headers cannot be used to change the behavior of HTTP methods
Media Types
|
|
Registered Media Types
Registered Media Types | Description |
---|---|
text/plain | A plain text format with no specific content structure or markup. |
text/html | Content that is formatted using the HyperText Markup Language (HTML). |
image/jpeg | An image compression method that was standardized by the Joint Photographic Experts Group (JEPG). |
application/xml | Content that is structured using the Extensible Markup Language (XML). |
application/atom+xml | Content that uses the Atom Syndication Format (Atom), which is an XML-based format that structures data into lists known as feeds. |
application/javascript | Source code written in the JavaScript programming language. |
application/json | The JavaScript Object Notation (JSON) text-based format that is often used by programs to exchange structured data. |
Media Types Rules
- Application-specific media types should be used
- Media type negotiation should be supported when multiple representations are available
- Media type selection using a query parameter may be supported
Message Body Rules
- the resource representation should support JSON
- JSON must be well-formed
- XML and other formats are optional for the resource representation
- Additional envelopes must not be created
Hypermedia Representation Rules
- A consistent form should be used to represent links
- A consistent form should be used to represent link relations
- A consistent form should be used to advertise links
- A self link should be included in response message body representations
- Minimize the number of advertised “entry point” API URIs
- Links should be used to advertise a resource’s available actions in a state-sensitive manner
Media Type Representation Rules
- A consistent form should be used to represent media type formats
- A consistent form should be used to represent media type schemas
Error Representation Rules
- A consistent form should be used to represent errors
- A consistent form should be used to represent error responses
- Consistent error types should be used for common error conditions
Client Concerns Rules
- New URIs should be used to introduce new concepts
- Schemas should be used to manage representational form versions
- Entity tags should be used to manage representational state versions
- OAuth may be used to protect resources
- API management solutions may be used to protect resources
- The query component of a URI should be used to support partial responses
- The query component of a URI should be used to embed linked resources
- JSONP should be supported to provide multi-origin read access from JavaScript
Final Thoughts Principles
- REST API designs differ more than necessary
- A REST API should be designed, not coded
- Programmers and their organizations benefit from consistency
- A REST API should be created using a GUI tool