前言:
如今,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=red
GET /cars?seats<=2
GET /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 working
201 – OK – New resource has been created
204 – OK – The resource was successfully deleted
304 – Not Modified – The client can use cached data
400 – Bad Request
401 – Unauthorized
403 – Forbidden
404 – Not found
418 - URL too long
422 – 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"
}
]
}