web api guideline - sailing2014/Web-API-Guideline GitHub Wiki

Web API Guideline

Style


  • Pragmatic REST style

Domain


  • api.domain.net for API
Domain Means
domain.com main domain
api.domain.net Product ENV for API
dev.api.domain.net Dev ENV for API
test.api.domain.net Test ENV for API

Base URLs


  • Only nouns in base URLs

    • Keep verbs out of base URLs
    • Except that the API don't involve resources
  • Verbs for non-resources API

    • Example:
    /convert?from=ERU&to=CNY&amount=100
    
  • Versioning use /v1

    • Version is MUST
    • Let it to the LEFT in the URL
/v1/dogs
  • Optionally, the detail of version can be put in the header
dogs/1.2.1
Content-Type: application/json
  • Just use n rather than n.m (such as 1.0)
Case Example
Good /v1
Bad /v1.0
  • Intuitive plural and concrete names rather than singular and abstract names.
Case Example
Good /dogs, /cats
Bad /animal, /pet
  • Two base URLs per resource
    • One for the resource collection
/v1/dogs
    • Count of the collection
/v1/dogs/count
    • Another for the special resources
      • A single resource
/v1/dogs/1234
      • Some spacial resources
/v1/dogs/1234,5678,1357
  • Better URL depth: /resource/identifier/resource
    • Example:
/v1/owners/123/dogs
/v1/owners/123/dogs/1234

Query

  • Sweep complexity under the '?'
    • Example:
GET /v1/dogs?color=red&state=running&location=park
  • Fields in a comma delimited list for partial query
    • Example:
/v1/dogs?fields=name,color,location
  • limit and offset for paging, default limit = 10 and offset = 0

  • alt for multiple data format

?alt=json
?alt=xml
  • q for search

  • under bar as separator in one parameter

    • Example:
?suppress_response_codes=true
  • The following parameters MUST always transferred by POST
    • Password, and should be encrypted.
    • Token

Operation

  • Use HTTP methods to operate on the resource
Resource POST GET PUT DELETE
Means Create Read Update Delete
/v1/dogs Create a new dog List all of dogs Bulk update dogs Delete all dogs
/v1/dogs/1234 Error Get the dog with id 1234 If exists update dog 1234, if not, error Delete dog 1234
/v1/dogs/1234,5678 Error Get the dogs 1234 and 5678 If exists update, if not, error Delete dog 1234 and 5678

Authentication

Response

  • Use HTTP status codes
HTTP Status Code Means
200 Request successful
400 Parameter Error
401 Permission Denied
404 Not Found
500 Server Error
  • JSON as default data format
    • lowCamelCase for attributes
{
"createdAt": 1320296464,
"dateTime": ā€œ2011-10-29T09:35:00Zā€
}
  • Response code format
    • errorCode (MUST)
    • errorMessage (MUST)
    • data (MUST)
    • Example with JSON format:
{
    "errorCode": 0,
    "errorMessage": "Request successful!"
    "data": {
        "uid": "10000003",
        "token": "sess::8ddefbd4317b0d1c649025838d4019f2",
        "expiration": "2014-11-07 15:59:39"
    }
}