This post highlights some best practice for creating an API facade within your enterprise.
•Keep it simple using two base urls (/foo and /foo/123)
•Keep verbs out of the Url (use nouns only)
•Use all the HTTP verbs (GET, POST, PUT, DELETE)
•Use plural nouns and names that mean things (not “items”, but “cats”)
•Keep the depth of levels small – pretty much “/resource/id/resource” (/owners/123/cats).
•Put complex filtering behind the “?” (e.g. /foo?type=abc etc)
•Use HTTP status codes for errors (and success). Start with 200, 400 and 500.
•Further codes are 201 - Created, 304 - Not Modified, 404 – Not Found, 401 – Unauthorized.
•Create verbose messages – one for the developer and another for users.
•Never release an API without a version.
•Just use “/vN/foo” where N is an integer (e.g. /v3/foo/1234)
•Use the format in the header (Content-Type) if it doesn’t change the logic (e.g. oAuth) – put the format in the header (?a.json) if the logic changes. Use a period to separate the format (.json, .xml etc). JSON should be the default format.
•Allow partial response by allowing fields with commas (?fields=title,name) and sub-fields (?fields=title,media:group(media:thumbnail))
•Use limit and offset for pagination (/foo?limit=25&offset=50). Include metadata in the response to make subsequent requests easy to follow. Default with limit=10 and offset=0
•If the api request does not return a response, use a verb (/convert?from=X&to=Y&amount=100). Ensure documentation separates this kind of interface and indicates it does not return a response.
•Use camelCase for attribute names in the response.
•Perform a global search as /search?q=foo+bar
•Extend scoped search in a similar manner “/owners/123/dogs?q=foo”
•To format the response use the dot notation “/owners/123/dogs.xml?q=foo” (without the dot format will return the default json)
•Use api.domain.com and dev.domain.com as a portal
•Use suppress_response_codes = true in the querystring to allow the consumer to express they don’t want native HTTP codes in the response (due to Flash issues etc). The HTTP 200 is always returned but the response message contains the detail.
•Implementing an API façade pattern involves three basic steps. 1 - Design the ideal API – design the URLs, request parameters and responses, payloads, headers, query parameters, and so on. The API design should be self-consistent. 2 - Implement the design with data stubs. This allows application developers to use your API and give you feedback even before your API is connected.
Base on the excellent Web API Design document by Brian Mulloy