restful api设计最佳实践


参考github的api,总结一份实践经验,方便以后设计api查阅。

使用https

考虑api的安全性,建议使用https访问。 证书可使用let's encrypt的免费证书。

api访问地址与版本

访问地址使用统一的api前缀,或者使用二级域名,版本号建议显式的放在url中。 例如: https://www.iian.xyz/api/v1/users

交互结构

尽量采用json,提供替他类型的内容,使用accept声明可响应格式。客户端使用content-type来标记使用的格式。

url设计

操作针对资源进行,使用url来代表资源,使用http请求方法来指明进行的操作。 例如:

// 查询用户列表
GET: https://www.iian.xyz/api/v1/users
// 删除用户
DELETE: https://www.iian.xyz/api/v1/users/1
// 添加用户
POST: https://www.iian.xyz/api/v1/users
// 修改用户信息
PUT: https://www.iian.xyz/api/v1/users/1

查询与筛选

查询与筛选使用查询字符串。 例如:GET: https://www.iian.xyz/api/v1/users?page=1&per_page=10&keywords=aaa

响应信息

错误必须同时发送错误信息。 根据执行情况,选择对应的状态码进行返回。可以使用自定义的状态码,但是也应该同时指明响应的状态码。具体的响应状态码含义可以,可以访问这个网站

身份信息验证与权限验证

没有携带约定的身份信息,应该返回401。

401 UNAUTHORIZED The request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field1 containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field2. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.

而对于没有权限执行某个操作,建议使用404,防止嗅探。

404 NOT FOUND The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 Gone status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent. A 404 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls1.

限速、限流

对于接口的访问次数、流量限制,超过后建议使用429。

The user has sent too many requests in a given amount of time ("rate limiting"). The response representations SHOULD include details explaining the condition, and MAY include a Retry-After header indicating how long to wait before making a new request. Note that this specification does not define how the origin server identifies the user, nor how it counts requests. For example, an origin server that is limiting request rates can do so based upon counts of requests on a per-resource basis, across the entire server, or even among a set of servers. Likewise, it might identify the user by its authentication credentials, or a stateful cookie. Responses with the 429 status code MUST NOT be stored by a cache.

文档

文档应该声明接口的访问方法,接口地址,应该携带的请求头信息,响应格式,响应内容举例,错误码以及接口的使用场景。