Web API 入门系列 - RESTful API 设计指南

参考:https://developer.github.com/v3/  https://github.com/bolasblack/http-api-guide

HTTP 协议

目前使用HTTP1.1协议,为了通信安全,建议使用https协议

域名

尽量使用专业域名,如 https://api.github.com
也可以使用主域名,如 https://www.github.com/api


API版本

放在请求头里,如Accept: application/vnd.github.v3+json 这种方案URL比较优雅,表示同一资源,github api 推荐这样使用。

URL地址

在RESTful架构中,每个网址代表一种资源,用名称复数形式,不要用动词。
如应该使用: https://api.github.com/books 不应该使用:https://api.github.com/getbooks

过滤分页

分页:?page=2&per_page=100: 如:https://api.github.com/user/repos?page=2&per_page=100 如果没有传递时,使用默认配置。排序:?sortby=name&order=asc: 如:https://api.github.com/user/repos?page=2&per_page=100&sortby=name&order=asc 如果没有传递时,使用默认配置。
过滤:?username=1 如:https://api.github.com/user/repos?username=1

HTTP 动词

Restful 风格的程序推荐使用 http verbs 来操作服务器资源,让资源发生状态转变。

关于方法语义的说明:


GET: 用于从服务器获取某个资源的信息
完成请求后返回状态码 200 OK
完成请求后需要返回被请求的资源详细信息

POST: 用于创建新资源
创建完成后返回状态码 201 Created
完成请求后需要返回被创建的资源详细信息

PUT: 用于完整的替换资源或者创建指定身份的资源,比如创建 id 为 123 的某个资源
如果是创建了资源,则返回 201 Created
如果是替换了资源,则返回 200 OK
完成请求后需要返回被修改的资源详细信息

PATCH: 用于局部更新资源
完成请求后返回状态码 200 OK
完成请求后需要返回被修改的资源详细信息

DELETE: 用于删除某个资源
完成请求后返回状态码 204 No Content

异常处理

在调用接口的过程中,可能出现下列几种错误情况:

服务器维护中,503 状态码

HTTP/1.1 503 Service Unavailable
Retry-After: 3600
Content-Length: 41

{"message": "Service In the maintenance"}
发送了无法转化的请求体,400 状态码

HTTP/1.1 400 Bad Request
Content-Length: 35

{"message": "Problems parsing JSON"}
服务到期(比如付费的增值服务等), 403 状态码

HTTP/1.1 403 Forbidden
Content-Length: 29

{"message": "Service expired"}
因为某些原因不允许访问(比如被 ban ),403 状态码

HTTP/1.1 403 Forbidden
Content-Length: 29

{"message": "Account blocked"}
权限不够,403 状态码

HTTP/1.1 403 Forbidden
Content-Length: 31

{"message": "Permission denied"}
需要修改的资源不存在, 404 状态码

HTTP/1.1 404 Not Found
Content-Length: 32

{"message": "Resource not found"}
缺少了必要的头信息,428 状态码

HTTP/1.1 428 Precondition Required
Content-Length: 35

{"message": "Header User-Agent is required"}
发送了非法的资源,422 状态码

HTTP/1.1 422 Unprocessable Entity
Content-Length: 149

{
"message": "Validation Failed",
"errors": [
{
"resource": "Issue",
"field": "title",
"code": "required"
}
]
}
所有的 error 哈希表都有 resource, field, code 字段,以便于定位错误,code 字段则用于表示错误类型:


missing: This means a resource does not exist.
missing_field: This means a required field on a resource has not been set.
invalid: This means the formatting of a field is invalid. The documentation for that resource should be able to give you more specific information.
already_exists:This means another resource has the same value as this field. This can happen in resources that must have some unique key (such as Label names).

身份认证

使用OAuth 2.0验证,参考 http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

 

posted @ 2016-12-15 17:37  虎头  阅读(1392)  评论(0编辑  收藏  举报