返回 登录
0

设计RESTful API的最佳实践

昨天刚在哪里看到目前的趋势是,前端MVC化,后端REST化。今天Hacker News热文里就出现了 SupportFu和UltraHook创始人、全端程序员Vinay Sahni根据SupportFu API设计的实践写出的长文“Best Practices for Designing a Pragmatic RESTful API”。内容全面,非常实用,我们会逐步编译出来。

当你的数据模型已经开始稳定下来,需要为Web App创建公开API了。API设计的难点在于,一旦发布再想大改会非常困难,所以需要很早就能尽量做出正确决策。可是现在API设计方面没有太多现成的指导,设计者面临的选择很多:选用什么格式?怎么鉴别身份?是否应该版本化?

要使API易用、易于接受和足够灵活,应该遵循以下原则:

  • An API is a user interface for a developer - so put some effort into making it pleasant
  • Use RESTful URLs and actions
  • Use SSL everywhere, no exceptions
  • An API is only as good as its documentation - so have great documentation
  • Version via the URL, not via headers
  • Use query parameters for advanced filtering, sorting & searching
  • Provide a way to limit which fields are returned from the API
  • Return something useful from POST, PATCH & PUT requests
  • HATEOAS isn't practical just yet
  • Use JSON where possible, XML only if you have to
  • You should use camelCase with JSON, but snake_case is 20% easier to read
  • Pretty print by default & ensure gzip is supported
  • Don't use response envelopes by default
  • Consider using JSON for POST, PUT and PATCH request bodies
  • Paginate using Link headers
  • Provide a way to autoload related resource representations
  • Provide a way to override the HTTP method
  • Provide useful response headers for rate limiting
  • Use token based authentication, transported over OAuth2 where delegation is needed
  • Include response headers that facilitate caching
  • Define a consumable error payload
  • Effectively use HTTP Status codes

Hacker News评论

评论