美文网首页REST架构风格研究
Resful Api接口命名规范

Resful Api接口命名规范

作者: 杨斌_1024 | 来源:发表于2020-04-26 19:04 被阅读0次

    URI是什么

    URI仅仅是一个概念,他规定在网络上定位一个资源的方式,描述的是一个资源,而url是他的一种实现方式,url是可以访问的。

    URI = scheme “://” authority “/” path [ “?” query ][ “#” fragment ]

    scheme: 指底层用的协议,如http、https、ftp

    host: 服务器的IP地址或者域名

    port: 端口,http中默认80

    path: 访问资源的路径,就是咱们各种web 框架中定义的route路由

    query: 为发送给服务器的参数

    fragment: 锚点,定位到页面的资源,锚点为资源id

    资源是什么

    在REST里面,信息可以抽象成为一个资源。任何一个东西都可以看作是资源,比如一本书,一种服务,甚至一些资源的集合,一个人等等都是资源。

    资源是一类实体的概念映射,不是某个特定的时刻关联的实体对象。

    The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. “today’s weather in Los Angeles”), a collection of other resources, a non-virtual object (e.g., a person), and so on. In other words, any concept that might be the target of an author’s hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

    一个资源即可是一个,比如一个客户,又可以是复数,比如全部客户。这些都可以看做资源。

    一个资源里面可以包含另一个资源。学校里包含班级,班级里有老师同学,这些都是资源。

    GitHub restful 接口设计例子

    GitHub restful 风格接口设计

    github案例

    resful资源命名规范

    1.用名词的复数去表示资源

    使用名词的主要原因是名词跟资源一样可以有属性,比如请求方法,传输什么格式的规定。

    http://api.example.com/device-management/managed-devices

    http://api.example.com/device-management/managed-devices/{device-id}

    http://api.example.com/user-management/admin

    2.命名格式一致

    在path里面把版本号写出来:v1/user-management/admin

    使用斜杠“/”来表示分层:user-management/admin

    使用"-"来代替一个资源里面的多个单词:managed-entities/{id}/install-script-location

    URI末尾不要有"/"

    URI里面不要有文件的类型标识

    URI应该是用小写字母

    3.在URI不要用CRUD,使用请求方式

    HTTP GET http://api.example.com/device-management/managed-devices  //Get all devices

    HTTP POST http://api.example.com/device-management/managed-devices  //Create new Device

    HTTP GET http://api.example.com/device-management/managed-devices/{id}  //Get device for given Id

    HTTP PUT http://api.example.com/device-management/managed-devices/{id}  //Update device for given Id

    HTTP DELETE http://api.example.com/device-management/managed-devices/{id}  //Delete device for given Id

    4.过滤查询的话用URI collection

    http://api.example.com/device-management/managed-devices?region=USA&brand=XYZ&sort=installation-date

    参考文档:REST Resource Naming Guide

    相关文章

      网友评论

        本文标题:Resful Api接口命名规范

        本文链接:https://www.haomeiwen.com/subject/ofujwhtx.html