RESTful介绍及示例

2020-07-19  本文已影响0人  张明学

RESTful的中文含义是“ 表现层状态传递”,完整表述是:Resource Representational State Transfer,简写成REST,其中Resource被省略了。

RESTful介绍


RESTful资源-Resource

RESTful中的Resource是网络中的资源,如“文本”、“图片”。
资源我们用URI来表示,重点用于表示资源的位置。

RESTful表现层-Representational

RESTful表现层是针对Resource,一个Resource可以用多种表示形式,如:文本的表现形式可以是:txt,html,xml等,图片的表现形式可以是:png,jpg 等。

表现层我们用http协议中的content-type和accept来表示,重点用于表示表现形式
Accept:application/json http://localhost:8080/book/123 表示请求json格式的book
Accept:application/xml http://localhost:8080/book/123 表示请求xml格式的book

RESTful状态转化-State Transfer

RESTful状态转化又是针对表现层的,分别用http的GET、POST、PUT、DELETE方法

RESTful的URI设计示例


RESTful 的核心思想也是通过这些动词 + 名词完成对资源的操作与访问。

URL 层级

单一资源的URL按上的规则就可以很好定义,但资源的相互关联与嵌套很常见,查找id是12的用户的所有帖子:

GET  /posts?userId=12

版本

通过 URL 加版本的方式可以更好的发现资源,如:

POST /v2/users
GET /V1/users/12

过滤/分页/排序

过滤

GET /users/12/posts?state=published,/users/12/posts?published=true

分页

GET /users?pageNo=1&pageSize=20

排序

GET /users?sort=score_desc
资源命名约定和URI格式
http://api.example.com/device-management
http://api.example.com/device-management/managed-devices
http://api.example.com/device-management/managed-devices/{id}
http://api.example.com/device-management/managed-devices/{id}/scripts
http://api.example.com/device-management/managed-devices/{id}/scripts/{id}
 http://api.example.com/device-management/managed-devices/
http://api.example.com/inventory-management/managed-entities/{id}/install-script-location(推荐)
http://api.example.com/inventory-management/managedEntities/{id}/installScriptLocation 
http://api.example.com/inventory-management/managed-entities/{id}/install-script-location (推荐)
http://api.example.com/inventory_management/managed_entities/{id}/install_script_location

参考:http://restful.p2hp.com

上一篇 下一篇

猜你喜欢

热点阅读