简简单单一篇文章,入门 RESTful URL 设计
2017-07-07 本文已影响83人
xiaojianxu
HTTP 是 REST 的封装(implementation)。
Verbs / 动作
Verb | Safe ? | Idempotent? | Scenario |
---|---|---|---|
OPTIONS | Y | Y | get communication options(at least available verbs) |
GET | Y | Y | get resource |
HEAD | Y | Y | same with GET but no response body |
PUT | N | Y | create(if not exists)/replace resource |
DELETE | N | Y | delete resource |
POST | N | N | create resource, unsafe operations there are no suitable verbs for |
PATCH | N | N | update resource partially |
与 RPC 风格 web 服务比较
RPC(SOAP):
- 只使用 HTTP POST 动作来传输封装打包的数据
- 重点是方法
- 重量级的
RESTful:
- 对 CRUD 的标准 HTTP 动作(POST, GET, PUT/PATCH, DELETE)
- 重点是资源,资源导向
- 轻量级的,跨平台容易
REST-RPC:
不封装,也是非标准 HTTP 动作,看见方法信息的 URI
参考资料:
Web API Design - Crafting Interfaces that Developers Love, you need to input your email to receive the ebook. [MUST READ] ‼️
http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
https://github.com/interagent/http-api-design
案例:
http://developer.github.com/v3
URL 设计原则
1、记住,REST 是以资源作为导向的。
2、对资源集使用复数名词形式(plural noun),如:/dogs
3、操作单个资源,使用 URL :/dogs/1234
4、使用正确的 HTTP 动词
5、共同的 CRUD 事例:
Resource | POST | GET | PUT | PATCH | DELETE |
---|---|---|---|---|---|
/dogs | create a new dog | list dogs | bulk update dogs | X | delete all dogs |
/dogs/1234 | X | show a dog | update a dog | Update a dog partially | delete a dog |