How to Design Better Restful API?

前言:

   如今,API已经成为一个提供服务重要方式或者途径。我一直从事后台服务系统的开发工作,深刻懂得一个结构清晰API的重要性。不成文的规定“ 对外提供web服务采用Restful风格,服务内部采用RPC”。

 

Google查阅一些文档,总结一下有9步。Check list

  •   ☑️ 使用名词,不要动词。

           GET         POST           PUT        DELETE/cars   获取汽车列表    创建一个汽车  更新所有汽车    删除所有汽车/cars/100  指定ID汽车    405       更新指定ID汽车  删除指定汽车note: 状态码=405   Method not allowed /getAllCars         ❌/createNewCar       ❌/deleteAllRedCars   ❌
  •   ☑️ GET只是用来查询数据,使用POST,PUT,DELETE状态

需要使用GET修改状态GET /users/711?activate   ❌
  • ☑️ 使用名词复数形式

/cars      代替  /car       ✅/users     代替  /user      ✅/products  代替  /product   ✅/settings  代替  /setting   ✅
  • ☑️ 用子资源表示关系

GET /cars/110/drivers/    表示 汽车ID为110的司机列表信息GET /cars/110/drivers/4   表示 汽车ID为110的司机ID为4的信息
  • ☑️ 使用HTTP Header约定客户端和服务端请求的格式

Accept: application/json;Content-Type: application/json
  • ☑️ 响应内容使用超文本连接来导航资源

{  "id": 120,  "manufacturer": "bmw",  "model": "X5",  "seats": 5,  "drivers": [   {    "id": "23",    "name": "Stefan Jauker",    "links": [     {     "rel": "self",     "href": "/api/v1/drivers/23"    }   ]  } ]}
  • ☑️ Query提供过滤功能

GET /cars?color=redGET /cars?seats<=2GET /cars?sort=-manufactorer,+model GET /cars?offset=10&limit=5 GET /cars?fields=manufacturer,model,id,color
  • ☑️ 使用API版本

xxx/api/v1
  • ☑️ 使用HTTP响应状态码来处理错误

200 – OK – Eyerything is working201 – OK – New resource has been created204 – OK – The resource was successfully deleted
304 – Not Modified – The client can use cached data
400 – Bad Request 401 – Unauthorized403 – Forbidden404 – Not found418 - URL too long422 – Unprocessable Entity
500 – Internal Server Error

特别强调一下500表示内部错误,但是单纯的返回错误栈信息没有帮助。错误调用栈应该被日志记录而不是返回给客户端。系统报错应该返回如下信息

{  "errors": [   {    "userMessage": "Sorry, the requested resource does not exist",    "internalMessage": "No car found in the database",    "code": 34,    "more info": "http://www.xxx.com/blog/api/v1/errors/12345"   }  ]}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cugriver

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值