├── .gitignore ├── LICENSE.md ├── SUPPLEMENT.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.sw[a-z] 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## License 2 | 3 | Copyright the [project contributors](https://github.com/bolasblack/http-api-guide/graphs/contributors). 4 | 5 | Released under a [MIT License](http://opensource.org/licenses/MIT). 6 | -------------------------------------------------------------------------------- /SUPPLEMENT.md: -------------------------------------------------------------------------------- 1 | # 补充内容 2 | 3 | 这里是一些补充性质的内容,在需要实现某些功能时可以做一个参考,不一定有相应的标准可以遵循。 4 | 5 | ## 目录 6 | 7 | * [扩充巴科斯范式](#user-content-扩充巴科斯范式-abnf) 8 | * [User-Agent](#user-content-user-agent) 9 | * [两步验证](#user-content-两步验证) 10 | * [同时操作多个资源](#user-content-同时操作多个资源) 11 | * [超文本驱动](#user-content-超文本驱动) 12 | 13 | ## 扩充巴科斯范式 (ABNF) 14 | 15 | 这算是阅读规范的预备知识吧,但写在 README 里还是太占空间了,所以写在了这里。 16 | 17 | 规范里类似: 18 | 19 | ```abnf 20 | header-field = field-name ":" OWS field-value OWS 21 | 22 | field-name = token 23 | field-value = *( field-content / obs-fold ) 24 | field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] 25 | field-vchar = VCHAR / obs-text 26 | 27 | obs-fold = CRLF 1*( SP / HTAB ) 28 | ; obsolete line folding 29 | ; see Section 3.2.4 30 | ``` 31 | 32 | 格式的内容叫做“扩充巴科斯范式”,是由 [RFC 5234](http://tools.ietf.org/html/rfc5234) ([Wikipedia](http://zh.wikipedia.org/wiki/%E6%89%A9%E5%85%85%E5%B7%B4%E7%A7%91%E6%96%AF%E8%8C%83%E5%BC%8F)) 定义用以描述一些内容的详细格式的定义语言。 33 | 34 | ## User-Agent 35 | 36 | 请求头中的 `User-Agent` 可以帮助服务端收集设备信息,但格式需要遵循 [RFC 7231](http://tools.ietf.org/html/rfc7231#section-5.5.3) 中的定义,下文是一些建议格式: 37 | 38 | * iOS 39 | 40 | iOS/iOS版本号 (设备型号; 是否越狱; 网络类型; 语言) CFBundleIdentifier/CFBundleVersion 41 | 42 | * Android 43 | 44 | Android/Android版本号 (设备型号; ROM版本号; 是否root; 网络类型; 语言) PackageName/PackageVersion 45 | 46 | * Web 应用的 User-Agent 由浏览器设定 47 | 48 | 示例: 49 | 50 | User-Agent: iOS/6.1.2 (iPhone 5; jailbroken; Wi-Fi; zh-CN) com.bundle.id/3.2 51 | 52 | User-Agent: Android/4.2 (MI-ONE Plus; MIUI-2.3.6f; unrooted; GPRS; zh-TW) com.bundle.id/2.1 53 | 54 | Android 的网络类型获取可以参考文档:[http://developer.android.com/reference/android/telephony/TelephonyManager.html](http://developer.android.com/reference/android/telephony/TelephonyManager.html) 55 | 56 | ## 两步验证 57 | 58 | 如果只是打算简单实现,建议使用 [TOTP](http://tools.ietf.org/html/rfc6238)([Wikipedia](http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm)) 协议,可以兼容 [Google Authenticator](https://code.google.com/p/google-authenticator/) 。 59 | 60 | 相关资料: 61 | 62 | * 这里是一份 TOTP 协议中密码生成算法的简单说明:[http://jacob.jkrall.net/totp/](http://jacob.jkrall.net/totp/) 63 | * [What are the advantages of TOTP over HOTP?](http://crypto.stackexchange.com/questions/2220/what-are-the-advantages-of-totp-over-hotp) 64 | 65 | ## 同时操作多个资源 66 | 67 | ### 创建多个相同的资源 68 | 69 | 请求: 70 | 71 | ```http 72 | POST /resources HTTP/1.1 73 | 74 | [{ 75 | "id": "1 也允许由客户端直接指定 ID ,比如 UUID", 76 | "name": "resource1", 77 | "property": "a" 78 | }, { 79 | "name": "resource2", 80 | "property": "b" 81 | }, { 82 | "name": "resource3", 83 | "property": "c" 84 | }] 85 | ``` 86 | 87 | 响应: 88 | 89 | ```http 90 | HTTP/1.1 201 Created 91 | Location: /resources/1,2,3 92 | 93 | [{ 94 | "id": "1", 95 | "name": "resource1", 96 | "property": "a" 97 | }, { 98 | "id": "2", 99 | "name": "resource2", 100 | "property": "b" 101 | }, { 102 | "id": "3", 103 | "name": "resource3", 104 | "property": "c" 105 | }] 106 | ``` 107 | 108 | ### 删除多个相同的资源 109 | 110 | ```http 111 | // 请求 112 | DELETE /resources/1,2,3 HTTP/1.1 113 | 114 | // 响应 115 | HTTP/1.1 204 No Content 116 | ``` 117 | 118 | ### 修改多个相同的资源 119 | 120 | 请求: 121 | 122 | ```http 123 | PATCH /resources/1,2,3 HTTP/1.1 124 | 125 | Content-Type: application/json 126 | { 127 | "property": "d" 128 | } 129 | 130 | // 也可以使用 JSON Patch 131 | Content-Type: application/json-patch+json 132 | { 133 | "op": "replace", 134 | "replace": "/property", 135 | "value": "d" 136 | } 137 | ``` 138 | 139 | 请求实体可以直接写一个 JSON 进行修改,也可以发送一个 [JSON Patch](http://tools.ietf.org/html/rfc6902) 进行修改。 140 | 141 | 响应: 142 | 143 | ```http 144 | HTTP/1.1 204 No Content 145 | ``` 146 | 147 | ## 超文本驱动 148 | 149 | 想法受启发于 [JSON API 方案](http://jsonapi.org/),很多做法基本照搬,主要是把 `links` 相关内容放到了请求头里。 150 | 151 | 想法目前还不成熟,并不建议投入使用。 152 | 153 | ```http 154 | HTTP/1.1 200 OK 155 | Link: ; rel="res:author"; allow="collection,get", 156 | ; rel="res:comments"; allow="collection,create,get,delete", 157 | ; rel="res:order"; allow="get,put" 158 | 159 | [{ 160 | "id": "1", 161 | "title": "Rails is Omakase", 162 | "author": "9", 163 | "comments": [ "5", "12", "17", "20" ] 164 | }] 165 | ``` 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HTTP 接口设计指北 2 | 3 | * 文档主要目的是为设计接口时提供建议,使大家不必重复造 HTTP 协议已经完成的轮子 4 | * **只是建议,不是必须遵从的要求** 5 | * 大家有什么问题想法或者建议欢迎 [创建 Issue](https://github.com/bolasblack/http-api-guide/issues/new) 或者 [提交 Pull Request](https://github.com/bolasblack/http-api-guide/compare/) 6 | 7 | ## 目录 8 | 9 | * [HTTP 协议](#user-content-http-协议) 10 | * [URL](#user-content-url) 11 | * [空字段](#user-content-空字段) 12 | * [国际化](#user-content-国际化) 13 | * [请求方法](#user-content-请求方法) 14 | * [状态码](#user-content-状态码) 15 | * [错误处理](#user-content-错误处理) 16 | * [身份验证](#user-content-身份验证) 17 | * [超文本驱动和资源发现](#user-content-超文本驱动和资源发现) 18 | * [分页](#user-content-分页) 19 | * [数据缓存](#user-content-数据缓存) 20 | * [并发控制](#user-content-并发控制) 21 | * [跨域](#user-content-跨域) 22 | * [其他资料](#user-content-其他资料) 23 | * [更细节的接口设计指南](#user-content-更细节的接口设计指南) 24 | 25 | ## HTTP 协议 26 | 27 | ### HTTP/1.1 28 | 29 | 2014 年 6 月的时候 IETF 已经正式的废弃了 [RFC 2616](http://tools.ietf.org/html/rfc2616) ,将它拆分为六个单独的协议说明,并重点对原来语义模糊的部分进行了解释: 30 | 31 | * RFC 7230 - HTTP/1.1: [Message Syntax and Routing](http://tools.ietf.org/html/rfc7230) - low-level message parsing and connection management 32 | * RFC 7231 - HTTP/1.1: [Semantics and Content](http://tools.ietf.org/html/rfc7231) - methods, status codes and headers 33 | * RFC 7232 - HTTP/1.1: [Conditional Requests](http://tools.ietf.org/html/rfc7232) - e.g., If-Modified-Since 34 | * RFC 7233 - HTTP/1.1: [Range Requests](http://tools.ietf.org/html/rfc7233) - getting partial content 35 | * RFC 7234 - HTTP/1.1: [Caching](http://tools.ietf.org/html/rfc7234) - browser and intermediary caches 36 | * RFC 7235 - HTTP/1.1: [Authentication](http://tools.ietf.org/html/rfc7235) - a framework for HTTP authentication 37 | 38 | 相关资料: 39 | 40 | * [RFC2616 is Dead](https://www.mnot.net/blog/2014/06/07/rfc2616_is_dead) ([中文版](http://www.infoq.com/cn/news/2014/06/http-11-updated)) 41 | 42 | ### HTTP/2 43 | 44 | HTTP 协议的 2.0 版本还没有正式发布,但目前已经基本稳定下来了。 45 | 46 | [2.0 版本的设计目标是尽量在使用层面上保持与 1.1 版本的兼容,所以,虽然数据交换的格式发生了变化,但语义基本全部被保留下来了](http://http2.github.io/http2-spec/index.html#rfc.section.8)。 47 | 48 | 因此,作为使用者而言,我们并不需要为了支持 2.0 而大幅修改代码。 49 | 50 | * [HTTP/2 latest draft](http://http2.github.io/http2-spec/index.html) 51 | * [HTTP/2 草案的中文版](https://github.com/fex-team/http2-spec/blob/master/HTTP2%E4%B8%AD%E8%8B%B1%E5%AF%B9%E7%85%A7%E7%89%88(06-29).md) 52 | * [HTTP/1.1 和 HTTP/2 数据格式的对比](http://http2.github.io/http2-spec/index.html#rfc.section.8.1.3) 53 | 54 | ## URL 55 | 56 | HOST 地址: 57 | 58 | https://api.example.com 59 | 60 | 所有 URI 都需要遵循 [RFC 3986](http://tools.ietf.org/html/rfc3986) 的要求。 61 | 62 | **强烈建议 API 部署 SSL 证书**,这样接口传递的数据的安全性才能都得一定的保障。 63 | 64 | ## 空字段 65 | 66 | 接口遵循“输入宽容,输出严格”原则,输出的数据结构中空字段的值一律为 `null` 67 | 68 | ## 国际化 69 | 70 | ### 语言标签 71 | 72 | [RFC 5646](http://tools.ietf.org/html/rfc5646) ([BCP 47](http://tools.ietf.org/html/bcp47)) 规定的语言标签的格式如下: 73 | 74 | ``` 75 | language-script-region-variant-extension-privateuse 76 | ``` 77 | 78 | 1. `language`:这部分使用的是 ISO 639-1, ISO 639-2, ISO 639-3, ISO 639-5 中定义的语言代码,必填 79 | * 这个部分由 `primary-extlang` 两个部分构成 80 | * `primary` 部分使用 ISO 639-1, ISO 639-2, ISO 639-3, ISO 639-5 中定义的语言代码,优先使用 ISO 639-1 中定义的条目,比如汉语 `zh` 81 | * `extlang` 部分是在某些历史性的兼容性的原因,在需要非常细致地区别 `primary` 语言的时候使用,使用 ISO 639-3 中定义的三个字母的代码,比如普通话 `cmn` 82 | * 虽然 `language` 可以只写 `extlang` 省略 `primary` 部分,但出于兼容性的考虑,还是**建议**加上 `primary` 部分 83 | 2. `script`: 这部分使用的是 [ISO 15924](http://www.unicode.org/iso15924/codelists.html) ([Wikipedia](http://zh.wikipedia.org/wiki/ISO_15924)) 中定义的语言代码,比如简体汉字是 `zh-Hans` ,繁体汉字是 `zh-Hant` 。 84 | 3. `region`: 这部分使用的是 [ISO 3166-1][iso3166-1] ([Wikipedia][iso3166-1_wiki]) 中定义的地理区域代码,比如 `zh-Hans-CN` 就是中国大陆使用的简体中文。 85 | 4. `variant`: 用来表示 `extlang` 的定义里没有包含的方言,具体的使用方法可以参考 [RFC 5646](http://tools.ietf.org/html/rfc5646#section-2.2.5) 。 86 | 5. `extension`: 用来为自己的应用做一些语言上的额外的扩展,具体的使用方法可以参考 [RFC 5646](http://tools.ietf.org/html/rfc5646#section-2.2.6) 。 87 | 6. `privateuse`: 用来表示私有协议中约定的一些语言上的区别,具体的使用方法可以参考 [RFC 5646](http://tools.ietf.org/html/rfc5646#section-2.2.7) 。 88 | 89 | 其中只有 `language` 部分是必须的,其他部分都是可选的;不过为了便于编写程序,建议设计接口时约定语言标签的结构,比如统一使用 `language-script-region` 的形式( `zh-Hans-CN`, `zh-Hant-HK` 等等)。 90 | 91 | 语言标签是大小写不敏感的,但按照惯例,建议 `script` 部分首字母大写, `region` 部分全部大写,其余部分全部小写。 92 | 93 | **有一点需要注意,任何合法的标签都必须经过 IANA 的认证,已通过认证的标签可以在[这个网页](http://www.iana.org/assignments/language-subtag-registry)查到。此外,网上还有一个非官方的[标签搜索引擎](http://people.w3.org/rishida/utils/subtags/)。** 94 | 95 | 相关资料: 96 | 97 | * ISO 639-1 Code List ([Wikipedia](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)) 98 | * [ISO 639-2 Code List](http://www.loc.gov/standards/iso639-2/php/code_list.php) ([Wikipedia](https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes)) 99 | * [ISO 639-3 Code List](http://www-01.sil.org/iso639-3/codes.asp?order=639_3&letter=%25) 100 | * [ISO 639-5 Code List](http://www.loc.gov/standards/iso639-5/id.php) ([Wikipedia](https://en.wikipedia.org/wiki/List_of_ISO_639-5_codes)) 101 | * [ISO 639-3 Macrolanguage Mappings](http://www-01.sil.org/iso639-3/macrolanguages.asp) ([Wikipedia](https://en.wikipedia.org/wiki/ISO_639_macrolanguage)) 102 | * [Relationship between ISO 639-3 and the other parts of ISO 639](http://www-01.sil.org/iso639-3/relationship.asp) 103 | * [网页头部的声明应该是用 lang="zh" 还是 lang="zh-cn"? - 知乎](http://www.zhihu.com/question/20797118) 104 | * [IETF language tag - Wikipedia](https://en.wikipedia.org/wiki/IETF_language_tag) 105 | * [语种名称代码](http://www.ruanyifeng.com/blog/2008/02/codes_for_language_names.html) :文中对带有方言( `extlang` )部分的标签介绍有误 106 | * [Language tags in HTML and XML](http://www.w3.org/International/articles/language-tags/) 107 | * [Choosing a Language Tag](http://www.w3.org/International/questions/qa-choosing-language-tags) 108 | 109 | ### 时区 110 | 111 | 客户端请求服务器时,如果对时间有特殊要求(如某段时间每天的统计信息),则可以参考 [IETF 相关草案](http://tools.ietf.org/html/draft-sharhalakis-httptz-05) 增加请求头 `Timezone` 。 112 | 113 | ``` 114 | Timezone: 2007-06-12T23:48:22+0800 115 | // OR 116 | Timezone: 1977-07-30T12:00:11+0200;;Europe/Athens 117 | ``` 118 | 119 | 时区的名称可以参考 [tz datebase](http://www.iana.org/time-zones)([Wikipedia](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)) 。 120 | 121 | 如果客户端请求时没有指定相应的时区,则服务端默认使用 [UTC](http://zh.wikipedia.org/wiki/%E5%8D%8F%E8%B0%83%E4%B8%96%E7%95%8C%E6%97%B6) 时间返回相应数据。 122 | 123 | PS 考虑到存在[夏时制](https://en.wikipedia.org/wiki/Daylight_saving_time)这种东西,所以不推荐客户端在请求时使用 Offset 。 124 | 125 | ### 时间格式 126 | 127 | 时间格式遵循 [ISO 8601](https://www.iso.org/obp/ui/#iso:std:iso:8601:ed-3:v1:en)([Wikipedia](https://en.wikipedia.org/wiki/ISO_8601)) 建议的格式: 128 | 129 | * 日期 `2014-07-09` 130 | * 时间 `14:31:22+0800` 131 | * 具体时间 `2007-11-06T16:34:41Z` 132 | * 持续时间 `P1Y3M5DT6H7M30S` (表示在一年三个月五天六小时七分三十秒内) 133 | * 时间区间 `2007-03-01T13:00:00Z/2008-05-11T15:30:00Z` 、 `2007-03-01T13:00:00Z/P1Y2M10DT2H30M` 、 `P1Y2M10DT2H30M/2008-05-11T15:30:00Z` 134 | * 重复时间 `R3/2004-05-06T13:00:00+08/P0Y6M5DT3H0M0S` (表示从2004年5月6日北京时间下午1点起,在半年零5天3小时内,重复3次) 135 | 136 | 相关资料: 137 | 138 | * [What's the difference between ISO 8601 and RFC 3339 Date Formats?](http://stackoverflow.com/questions/522251/whats-the-difference-between-iso-8601-and-rfc-3339-date-formats) 139 | * [JSON风格指南 - Google 风格指南(中文版)](https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%B1%9E%E6%80%A7%E5%80%BC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B) 140 | 141 | ### 货币名称 142 | 143 | 货币名称可以参考 [ISO 4217](javascript:;)([Wikipedia](http://en.wikipedia.org/wiki/ISO_4217)) 中的约定,标准为货币名称规定了三个字母的货币代码,其中的前两个字母是 [ISO 3166-1][iso3166-1]([Wikipedia][iso3166-1_wiki]) 中定义的双字母国家代码,第三个字母通常是货币的首字母。在货币上使用这些代码消除了货币名称(比如 dollar )或符号(比如 $ )的歧义。 144 | 145 | 相关资料: 146 | 147 | * 《RESTful Web Services Cookbook 中文版》 3.9 节《如何在表述中使用可移植的数据格式》 148 | 149 | ## 请求方法 150 | 151 | * 如果请求头中存在 `X-HTTP-Method-Override` 或参数中存在 `_method`(拥有更高权重),且值为 `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTION`, `HEAD` 之一,则视作相应的请求方式进行处理 152 | * `GET`, `DELETE`, `HEAD` 方法,参数风格为标准的 `GET` 风格的参数,如 `url?a=1&b=2` 153 | * `POST`, `PUT`, `PATCH`, `OPTION` 方法 154 | * 默认情况下请求实体会被视作标准 json 字符串进行处理,当然,依旧推荐设置头信息的 `Content-Type` 为 `application/json` 155 | * 在一些特殊接口中(会在文档中说明),可能允许 `Content-Type` 为 `application/x-www-form-urlencoded` 或者 `multipart/form-data` ,此时请求实体会被视作标准 `POST` 风格的参数进行处理 156 | 157 | 关于方法语义的说明: 158 | 159 | * `OPTIONS` 用于获取资源支持的所有 HTTP 方法 160 | * `HEAD` 用于只获取请求某个资源返回的头信息 161 | * `GET` 用于从服务器获取某个资源的信息 162 | * 完成请求后返回状态码 `200 OK` 163 | * 完成请求后需要返回被请求的资源详细信息 164 | * `POST` 用于创建新资源 165 | * 创建完成后返回状态码 `201 Created` 166 | * 完成请求后需要返回被创建的资源详细信息 167 | * `PUT` 用于完整的替换资源或者创建指定身份的资源,比如创建 id 为 123 的某个资源 168 | * 如果是创建了资源,则返回 `201 Created` 169 | * 如果是替换了资源,则返回 `200 OK` 170 | * 完成请求后需要返回被修改的资源详细信息 171 | * `PATCH` 用于局部更新资源 172 | * 完成请求后返回状态码 `200 OK` 173 | * 完成请求后需要返回被修改的资源详细信息 174 | * `DELETE` 用于删除某个资源 175 | * 完成请求后返回状态码 `204 No Content` 176 | 177 | 相关资料: 178 | 179 | * [RFC 7231 中对请求方法的定义](http://tools.ietf.org/html/rfc7231#section-4.3) 180 | * [RFC 5789](http://tools.ietf.org/html/rfc5789) - PATCH 方法的定义 181 | * [维基百科](http://zh.wikipedia.org/wiki/%E8%B6%85%E6%96%87%E6%9C%AC%E4%BC%A0%E8%BE%93%E5%8D%8F%E8%AE%AE#.E8.AF.B7.E6.B1.82.E6.96.B9.E6.B3.95) 182 | 183 | ## 状态码 184 | 185 | ### 请求成功 186 | 187 | * 200 **OK** : 请求执行成功并返回相应数据,如 `GET` 成功 188 | * 201 **Created** : 对象创建成功并返回相应资源数据,如 `POST` 成功;创建完成后响应头中应该携带头标 `Location` ,指向新建资源的地址 189 | * 202 **Accepted** : 接受请求,但无法立即完成创建行为,比如其中涉及到一个需要花费若干小时才能完成的任务。返回的实体中应该包含当前状态的信息,以及指向处理状态监视器或状态预测的指针,以便客户端能够获取最新状态。 190 | * 204 **No Content** : 请求执行成功,不返回相应资源数据,如 `PATCH` , `DELETE` 成功 191 | 192 | ### 重定向 193 | 194 | **重定向的新地址都需要在响应头 `Location` 中返回** 195 | 196 | * 301 **Moved Permanently** : 被请求的资源已永久移动到新位置 197 | * 302 **Found** : 请求的资源现在临时从不同的 URI 响应请求 198 | * 303 **See Other** : 对应当前请求的响应可以在另一个 URI 上被找到,客户端应该使用 `GET` 方法进行请求 199 | * 307 **Temporary Redirect** : 对应当前请求的响应可以在另一个 URI 上被找到,客户端应该保持原有的请求方法进行请求 200 | 201 | ### 条件请求 202 | 203 | * 304 **Not Modified** : 资源自从上次请求后没有再次发生变化,主要使用场景在于实现[数据缓存](#user-content-数据缓存) 204 | * 409 **Conflict** : 请求操作和资源的当前状态存在冲突。主要使用场景在于实现[并发控制](#user-content-并发控制) 205 | * 412 **Precondition Failed** : 服务器在验证在请求的头字段中给出先决条件时,没能满足其中的一个或多个。主要使用场景在于实现[并发控制](#user-content-并发控制) 206 | 207 | ### 客户端错误 208 | 209 | * 400 **Bad Request** : 请求体包含语法错误 210 | * 401 **Unauthorized** : 需要验证用户身份,如果服务器就算是身份验证后也不允许客户访问资源,应该响应 `403 Forbidden` 211 | * 403 **Forbidden** : 服务器拒绝执行 212 | * 404 **Not Found** : 找不到目标资源 213 | * 405 **Method Not Allowed** : 不允许执行目标方法,响应中应该带有 `Allow` 头,内容为对该资源有效的 HTTP 方法 214 | * 406 **Not Acceptable** : 服务器不支持客户端请求的内容格式,但响应里会包含服务端能够给出的格式的数据,并在 `Content-Type` 中声明格式名称 215 | * 410 **Gone** : 被请求的资源已被删除,只有在确定了这种情况是永久性的时候才可以使用,否则建议使用 `404 Not Found` 216 | * 413 **Payload Too Large** : `POST` 或者 `PUT` 请求的消息实体过大 217 | * 415 **Unsupported Media Type** : 服务器不支持请求中提交的数据的格式 218 | * 422 **Unprocessable Entity** : 请求格式正确,但是由于含有语义错误,无法响应 219 | * 428 **Precondition Required** : 要求先决条件,如果想要请求能成功必须满足一些预设的条件 220 | 221 | ### 服务端错误 222 | 223 | * 500 **Internal Server Error** : 服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。 224 | * 501 **Not Implemented** : 服务器不支持当前请求所需要的某个功能。 225 | * 502 **Bad Gateway** : 作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应。 226 | * 503 **Service Unavailable** : 由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个 `Retry-After` 头用以标明这个延迟时间(内容可以为数字,单位为秒;或者是一个 [HTTP 协议指定的时间格式](http://tools.ietf.org/html/rfc2616#section-3.3))。如果没有给出这个 `Retry-After` 信息,那么客户端应当以处理 500 响应的方式处理它。 227 | 228 | `501` 与 `405` 的区别是:`405` 是表示服务端不允许客户端这么做,`501` 是表示客户端或许可以这么做,但服务端还没有实现这个功能 229 | 230 | 相关资料: 231 | 232 | * [RFC 里的状态码列表](http://tools.ietf.org/html/rfc7231#page-49) 233 | * [RFC 4918](http://tools.ietf.org/html/rfc4918) - 422 状态码的定义 234 | * [RFC 6585](http://tools.ietf.org/html/rfc6585) - 新增的四个 HTTP 状态码,[中文版](http://www.oschina.net/news/28660/new-http-status-codes) 235 | * [维基百科上的《 HTTP 状态码》词条](http://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81) 236 | * [Do I need to use http redirect code 302 or 307? - Stack Overflow](http://stackoverflow.com/questions/2467664/do-i-need-to-use-http-redirect-code-302-or-307) 237 | * [400 vs 422 response to POST of data](http://stackoverflow.com/questions/16133923/400-vs-422-response-to-post-of-data) 238 | 239 | ## 错误处理 240 | 241 | 在调用接口的过程中,可能出现下列几种错误情况: 242 | 243 | * 服务器维护中,`503` 状态码 244 | 245 | ```http 246 | HTTP/1.1 503 Service Unavailable 247 | Retry-After: 3600 248 | Content-Length: 41 249 | 250 | {"message": "Service In the maintenance"} 251 | ``` 252 | 253 | * 发送了无法转化的请求体,`400` 状态码 254 | 255 | ```http 256 | HTTP/1.1 400 Bad Request 257 | Content-Length: 35 258 | 259 | {"message": "Problems parsing JSON"} 260 | ``` 261 | 262 | * 服务到期(比如付费的增值服务等), `403` 状态码 263 | 264 | ```http 265 | HTTP/1.1 403 Forbidden 266 | Content-Length: 29 267 | 268 | {"message": "Service expired"} 269 | ``` 270 | 271 | * 因为某些原因不允许访问(比如被 ban ),`403` 状态码 272 | 273 | ```http 274 | HTTP/1.1 403 Forbidden 275 | Content-Length: 29 276 | 277 | {"message": "Account blocked"} 278 | ``` 279 | 280 | * 权限不够,`403` 状态码 281 | 282 | ```http 283 | HTTP/1.1 403 Forbidden 284 | Content-Length: 31 285 | 286 | {"message": "Permission denied"} 287 | ``` 288 | 289 | * 需要修改的资源不存在, `404` 状态码 290 | 291 | ```http 292 | HTTP/1.1 404 Not Found 293 | Content-Length: 32 294 | 295 | {"message": "Resource not found"} 296 | ``` 297 | 298 | * 缺少了必要的头信息,`428` 状态码 299 | 300 | ```http 301 | HTTP/1.1 428 Precondition Required 302 | Content-Length: 35 303 | 304 | {"message": "Header User-Agent is required"} 305 | ``` 306 | 307 | * 发送了非法的资源,`422` 状态码 308 | 309 | ```http 310 | HTTP/1.1 422 Unprocessable Entity 311 | Content-Length: 149 312 | 313 | { 314 | "message": "Validation Failed", 315 | "errors": [ 316 | { 317 | "resource": "Issue", 318 | "field": "title", 319 | "code": "missing_field" 320 | } 321 | ] 322 | } 323 | ``` 324 | 325 | 所有的 `error` 哈希表都有 `resource`, `field`, `code` 字段,以便于定位错误,`code` 字段则用于表示错误类型: 326 | 327 | * `missing`: 说明某个字段的值代表的资源不存在 328 | * `invalid`: 某个字段的值非法,接口文档中会提供相应的信息 329 | * `missing_field`: 缺失某个必须的字段 330 | * `already_exist`: 发送的资源中的某个字段的值和服务器中已有的某个资源冲突,常见于某些值全局唯一的字段,比如 @ 用的用户名(这个错误我有纠结,因为其实有 409 状态码可以表示,但是在修改某个资源时,很一般显然请求中不止是一种错误,如果是 409 的话,多种错误的场景就不合适了) 331 | 332 | ## 身份验证 333 | 334 | 部分接口需要通过某种身份验证方式才能请求成功(这些接口**应该**在文档中标注出来),合适的身份验证解决方案目前有两种: 335 | 336 | * [HTTP 基本认证](http://zh.wikipedia.org/wiki/HTTP%E5%9F%BA%E6%9C%AC%E8%AE%A4%E8%AF%81),**只有在部署了 SSL 证书的情况下才可以使用,否则用户密码会有暴露的风险,当然,最好不要使用** 337 | * [JSON Web Token](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25) ,支持通过登录接口使用账号密码获取,在请求接口时使用 `Authorization: Bearer #{token}` 头标或者 `token` 参数的值的方式进行验证。 338 | * [Json Web Tokens: Introduction](http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/) 339 | * [Json Web Tokens: Examples](http://angular-tips.com/blog/2014/05/json-web-tokens-examples/) 340 | * [Cookies vs Tokens. Getting auth right with Angular.JS](https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/) 341 | * [OAuth 2.0](https://tools.ietf.org/html/rfc6749) 342 | * [官网](http://oauth.net/2/) 343 | * [理解OAuth 2.0 - 阮一峰](http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html) 以及对[文中 `state` 参数的介绍的修正](http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html#comment-323002) 344 | 345 | ## 超文本驱动和资源发现 346 | 347 | REST 服务的要求之一,客户端不再需要将某些接口的 URI 硬编码在代码中,唯一需要存储的只是 API 的 HOST 地址,能够非常有效的降低客户端与服务端之间的耦合,服务端对 URI 的任何改动都不会影响到客户端的稳定。 348 | 349 | 目前只有几种方案差强人意: 350 | 351 | * [JSON HAL 草案](http://tools.ietf.org/html/draft-kelly-json-hal-06) ,示例可以参考 [JSON HAL 作者自己的介绍](http://stateless.co/hal_specification.html) 352 | * [GitHub API 使用的方案](https://developer.github.com/v3/#hypermedia) ,应该是一种 JSON HAL 的变体 353 | * [JSON API 方案](http://jsonapi.org/) (这里有 [@迷渡](https://github.com/justjavac) 发起的 [中文版](http://jsonapi.org.cn/) ),另外一种类似 JSON HAL 的方案,不过某些方面(比如甚至也考虑到了 URL )考虑的比 JSON HAL 更为具体 354 | 355 | 目前来看应该是合并 JSON API 和 JSON HAL 两个方案的做法,各取所长,能够得到一个相对理想的方案 356 | 357 | ## 分页 358 | 359 | 请求某个资源集合时,可以通过指定 `count` 参数来指定每页的资源数量,通过 `page` 参数指定页码,或根据 `last_cursor` 参数指定上一页最后一个资源的标识符。 360 | 361 | 如果没有传递 `count` 参数或者 `count` 参数的值为空,则使用默认值 20 , `count` 参数的最大上限为 100 。 362 | 363 | 如何同时传递了 `last_cursor` 和 `page` 参数,则使用 `page` 。 364 | 365 | 分页的相关信息会包含在 [Link Header](http://tools.ietf.org/html/rfc5988) 和 `X-Total-Count` 中。 366 | 367 | 如果是第一页或者是最后一页时,不会返回 `previous` 和 `next` 的 Link 。 368 | 369 | ```http 370 | HTTP/1.1 200 OK 371 | X-Total-Count: 542 372 | Link: ; rel="first", 373 | ; rel="last" 374 | ; rel="previous", 375 | ; rel="next", 376 | 377 | [ 378 | ... 379 | ] 380 | ``` 381 | 382 | 相关资料: 383 | 384 | * [RFC 5005 第3节 _Paged Feeds_](http://tools.ietf.org/html/rfc5005#section-3) 385 | * [RFC 5988 6.2.2节 _Initial Registry Contents_](http://tools.ietf.org/html/rfc5988#section-6.2.2) 386 | 387 | ## 数据缓存 388 | 389 | 大部分接口应该在响应头中携带 `Last-Modified`, `ETag`, `Vary`, `Date` 信息,客户端可以在随后请求这些资源的时候,在请求头中使用 `If-Modified-Since`, `If-None-Match` 等请求头来确认资源是否经过修改。 390 | 391 | 如果资源没有进行过修改,那么就可以响应 `304 Not Modified` 并且不在响应实体中返回任何内容。 392 | 393 | ```bash 394 | $ curl -i http://api.example.com/#{RESOURCE_URI} 395 | HTTP/1.1 200 OK 396 | Cache-Control: public, max-age=60 397 | Date: Thu, 05 Jul 2012 15:31:30 GMT 398 | Vary: Accept, Authorization 399 | ETag: "644b5b0155e6404a9cc4bd9d8b1ae730" 400 | Last-Modified: Thu, 05 Jul 2012 15:31:30 GMT 401 | 402 | Content 403 | ``` 404 | 405 | ```bash 406 | $ curl -i http://api.example.com/#{RESOURCE_URI} -H "If-Modified-Since: Thu, 05 Jul 2012 15:31:30 GMT" 407 | HTTP/1.1 304 Not Modified 408 | Cache-Control: public, max-age=60 409 | Date: Thu, 05 Jul 2012 15:31:45 GMT 410 | Vary: Accept, Authorization 411 | Last-Modified: Thu, 05 Jul 2012 15:31:30 GMT 412 | ``` 413 | 414 | ```bash 415 | $ curl -i http://api.example.com/#{RESOURCE_URI} -H 'If-None-Match: "644b5b0155e6404a9cc4bd9d8b1ae730"' 416 | HTTP/1.1 304 Not Modified 417 | Cache-Control: public, max-age=60 418 | Date: Thu, 05 Jul 2012 15:31:55 GMT 419 | Vary: Accept, Authorization 420 | ETag: "644b5b0155e6404a9cc4bd9d8b1ae730" 421 | Last-Modified: Thu, 05 Jul 2012 15:31:30 GMT 422 | ``` 423 | 424 | 相关资料: 425 | 426 | * [RFC 7232](http://tools.ietf.org/html/rfc7232) 427 | * [HTTP 缓存 - Google Developers](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=zh-cn) 428 | * [RFC 2616 中缓存过期时间的算法](http://tools.ietf.org/html/rfc2616#section-13.2.3), [MDN 版](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching_FAQ), [中文版](http://blog.csdn.net/woxueliuyun/article/details/41077671) 429 | * [HTTP 协议中 Vary 的一些研究](https://www.imququ.com/post/vary-header-in-http.html) 430 | * [Cache Control 與 ETag](https://blog.othree.net/log/2012/12/22/cache-control-and-etag/) 431 | 432 | ## 并发控制 433 | 434 | 不严谨的实现,或者缺少并发控制的 `PUT` 和 `PATCH` 请求可能导致 “更新丢失”。这个时候可以使用 `Last-Modified` 和/或 `ETag` 头来实现条件请求,支持乐观并发控制。 435 | 436 | 下文只考虑使用 `PUT` 和 `PATCH` 方法更新资源的情况。 437 | 438 | * 客户端发起的请求如果没有包含 `If-Unmodified-Since` 或者 `If-Match` 头,那就返回状态码 `403 Forbidden` ,在响应正文中解释为何返回该状态码 439 | * 客户端发起的请求提供的 `If-Unmodified-Since` 或者 `If-Match` 头与服务器记录的实际修改时间或 `ETag` 值不匹配的时候,返回状态码 `412 Precondition Failed` 440 | * 客户端发起的请求提供的 `If-Unmodified-Since` 或者 `If-Match` 头与服务器记录的实际修改时间或 `ETag` 的历史值匹配,但资源已经被修改过的时候,返回状态码 `409 Conflict` 441 | * 客户端发起的请求提供的条件符合实际值,那就更新资源,响应 `200 OK` 或者 `204 No Content` ,并且包含更新过的 `Last-Modified` 和/或 `ETag` 头,同时包含 `Content-Location` 头,其值为更新后的资源 URI 442 | 443 | 相关资料: 444 | 445 | * 《RESTful Web Services Cookbook 中文版》 10.4 节 《如何在服务器端实现条件 PUT 请求》 446 | * [RFC 7232 "Conditional Requests"](https://tools.ietf.org/html/rfc7232) 447 | * [Location vs. Content-Location](https://www.subbu.org/blog/2008/10/location-vs-content-location) 448 | 449 | ## 跨域 450 | 451 | ### CORS 452 | 453 | 接口支持[“跨域资源共享”(Cross Origin Resource Sharing, CORS)](http://www.w3.org/TR/cors),[这里](http://enable-cors.org/)和[这里](http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity)和[这份中文资料](http://newhtml.net/using-cors/)有一些指导性的资料。 454 | 455 | 简单示例: 456 | 457 | ```bash 458 | $ curl -i https://api.example.com -H "Origin: http://example.com" 459 | HTTP/1.1 302 Found 460 | ``` 461 | 462 | ```bash 463 | $ curl -i https://api.example.com -H "Origin: http://example.com" 464 | HTTP/1.1 302 Found 465 | Access-Control-Allow-Origin: * 466 | Access-Control-Expose-Headers: ETag, Link, X-Total-Count 467 | Access-Control-Allow-Credentials: true 468 | ``` 469 | 470 | 预检请求的响应示例: 471 | 472 | ```bash 473 | $ curl -i https://api.example.com -H "Origin: http://example.com" -X OPTIONS 474 | HTTP/1.1 302 Found 475 | Access-Control-Allow-Origin: * 476 | Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With 477 | Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE 478 | Access-Control-Expose-Headers: ETag, Link, X-Total-Count 479 | Access-Control-Max-Age: 86400 480 | Access-Control-Allow-Credentials: true 481 | ``` 482 | 483 | ### JSON-P 484 | 485 | 如果在任何 `GET` 请求中带有参数 `callback` ,且值为非空字符串,那么接口将返回如下格式的数据 486 | 487 | ```bash 488 | $ curl http://api.example.com/#{RESOURCE_URI}?callback=foo 489 | ``` 490 | 491 | ```javascript 492 | foo({ 493 | "meta": { 494 | "status": 200, 495 | "X-Total-Count": 542, 496 | "Link": [ 497 | {"href": "http://api.example.com/#{RESOURCE_URI}?cursor=0&count=100", "rel": "first"}, 498 | {"href": "http://api.example.com/#{RESOURCE_URI}?cursor=90&count=100", "rel": "prev"}, 499 | {"href": "http://api.example.com/#{RESOURCE_URI}?cursor=120&count=100", "rel": "next"}, 500 | {"href": "http://api.example.com/#{RESOURCE_URI}?cursor=200&count=100", "rel": "last"} 501 | ] 502 | }, 503 | "data": // data 504 | }) 505 | ``` 506 | 507 | ## 其他资料 508 | 509 | * [Httpbis Status Pages](https://tools.ietf.org/wg/httpbis/) 510 | * [所有在 IANA 注册的消息头和相关标准的列表](http://www.iana.org/assignments/message-headers/message-headers.xhtml) 511 | 512 | ## 更细节的接口设计指南 513 | 514 | 这里还有一些其他参考资料: 515 | 516 | * 推荐参考文档 [HTTP API Design Guide](https://github.com/interagent/http-api-design/) 来设计 REST 风格的 API ,只有以下两点我个人并不建议参考: 517 | * [Use consistent path formats](https://github.com/interagent/http-api-design/#use-consistent-path-formats) 518 | 还是不建议将动作写在 URL 中,像文档中的情况,可以将这个行为抽象成一个事务资源 `POST /runs/:run_id/stop-logs` 或者 `POST /runs/:run_id/stoppers` 来解决 519 | * [Paginate with Ranges](https://github.com/interagent/http-api-design/#paginate-with-ranges) 520 | 确实是一个巧妙的设计,但似乎并不符合 `Content-Range` 的设计意图,而且有可能和需要使用到 `Content-Range` 的正常场景冲突(虽然几乎不可能),所以不推荐 521 | * [Best Practices for Designing a Pragmatic RESTful API](http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api) 522 | * [Thoughts on RESTful API Design](http://restful-api-design.readthedocs.org/en/latest/) 523 | * [The RESTful CookBook](http://restcookbook.com/) 524 | 525 | [iso3166-1]: javascript:; 526 | [iso3166-1_wiki]: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 527 | --------------------------------------------------------------------------------