文章
问答
冒泡
restful风格接口范例
在restful风格中,所有的对象都是资源,所有的接口都是资源的表现形式。大多数人对CRUD的接口可以理解,但是对资源的操作也不是局限于CRUD的。
这里以文章为例,写几个restful风格的范例。
 
描述
范例
Method
uri
query
body
创建文章
/articles
POST
/articles
 
{"content":""}
删除文章
/articles/{id}
DELETE
/articles/{id}
   
修改文章
/articles/{id}
PUT
/articles/{id}
 
{"content":""}
根据ID查询文章
/articles/{id}
GET
/articles/{id}
   
查询文章列表
/artciles/all?tagId=1
GET
/artciles/all
tagId=1
 
查询文章列表(分页)
/atricles/page?pageNum=1&pageSize=10
GET
/atricles/page
pageNum=1&pageSize=10
 
根据name获取对应的文章
/articles/name/{name}
GET
/articles/name/{name}
   
根据多个字段查询一条数据
/articles/one?ownerId=1&name=name
GET
/articles/one
ownerId=1&name=name
 
文章新增或修改
/articles/upsert
PUT
/articles/upsert
 
{
"id": null,
"content":""
}
文章启用
/articles/{id}/enabled
PUT
/articles/{id}/enabled
   
文章禁用
/articles/{id}/disabled
PUT
/articles/{id}/disabled
   
批量插入文章
/articles/batch
POST
/articles/batch
 
[{"content":""}]
批量删除文章
/articles/batch?ownerId=1
DELETE
/articles/batch
ownerId=1
 
批量修改文章
/articles/batch?ownerId=1
PUT
/articles/batch
ownerId=1
[{"content":""}]
 
 
1.关于restful的返回值:
restful发返回值都是json格式,所以要么不返回,返回的只能是json。
要不要做一层包装?很多返回的对象是类似这样的
{ "status":"ok", "code":"200", "data":{} }
 
这种是没有问题的 ,但是,由于restful是基于http的,我们更倾向于基于http的状态码来判断。如果返回正常,则只返回有效数据,如果返回有异常,则返回的json是异常码和异常信息
正常返回
httpcode 200
response
{ "id":"1", "title":"test" }
异常返回
httpcode 460
{ "code":"ARTICLE_NOT_FOUND", "message":"文章未找到" }
2.版本问题
restful中每个uri都是一个资源,所以版本信息不建议加在uri中,例如这样
/v1/articles
我们更倾向于把版本信息放在header中
 
restful是一个风格,不是一个标准规范,你遵循它,可以当接口显得更加规范优雅,不遵循,也无所谓。活还是要干的,饭也是要吃的。
 

restful

关于作者

落雁沙
非典型码农
获得点赞
文章被阅读