Restful_api - zhongjiajie/zhongjiajie.github.com GitHub Wiki

REST API

REST API-最佳实现

10-best-practices-for-better-restful-api

通过10-best-practices-for-better-restful-api可以得出10个实践

  • Use nouns but no verbs

    should should not
    /cars /getAllCars
  • GET method and query parameters should not alter the state

    should should not
    POST /users/711/activate GET /users/711/activate
  • Use plural(复数) nouns

    should should not
    /cars /car
  • Use sub-resources for relations (If a resource is related to another resource use subresources)

    GET /cars/711/drivers/: Returns a list of drivers for car 711

  • Use HTTP headers for serialization formats

  • Use HATEOAS(Hypermedia as the Engine of Application State)

  • Provide filtering, sorting, field selection and paging for collections

    • Filtering: GET /cars?color=red Returns a list of red cars or GET /cars?seats<=2 Returns a list of cars with a maximum of 2 seats
    • Sorting: GET /cars?sort=-manufactorer,+model returns a list of cars sorted by descending manufacturers and ascending models.
    • Field selection: GET /cars?fields=manufacturer,model,id,color get方法只获取部分字段
    • Paging: GET /cars?offset=10&limit=5 To send the total entries back to the user use the custom HTTP header: X-Total-Count.
  • Version your API

    /blog/api/v1

  • Handle Errors with HTTP status codes(较常用的HTTP代码)

    HTTP代码 状态 含义
    200 OK Eyerything is working
    201 OK New resource has been created
    204 OK The resource was successfully deleted
    304 Not Modified The client can use cached data
    400 Bad Request The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. "The JSON is not valid"
    401 Unauthorized The request requires an user authentication
    403 Forbidden The server understood the request, but is refusing it or the access is not allowed
    404 Not found There is no resource behind the URI
    422 Unprocessable Entity Should be used if the server cannot process the enitity, e.g. if an image cannot be formatted or mandatory fields are missing in the payload
    500 Internal Server Error API developers should avoid this error. If an error occurs in the global catch blog, the stracktrace should be logged and not returned as response
  • Allow overriding HTTP method

    Some proxies support only POST and GET methods. To support a RESTful API with these limitations, the API needs a way to override the HTTP method.Use the custom HTTP Header X-HTTP-Method-Override to overrider the POST Method.


⚠️ **GitHub.com Fallback** ⚠️