HTTP 创建资源
示例
并不是每个人都对资源创建最语义上正确的方法达成共识。因此,您的API可以接受POST或PUT请求,也可以接受。
201Created如果资源创建成功,服务器应响应。如果没有,请选择最合适的错误代码。
例如,如果您提供用于创建员工记录的API,则请求/响应可能如下所示:
POST /employees HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "Charlie Smith",
"age": 38,
"job_title": "Software Developer",
"salary": 54895.00
}HTTP/1.1 201 Created
Location: /employees/1/charlie-smith
Content-Type: application/json
{
"employee": {
"name": "Charlie Smith",
"age": 38,
"job_title": "Software Developer",
"salary": 54895.00
"links": [
{
"uri": "/employees/1/charlie-smith",
"rel": "self",
"method": "GET"
},
{
"uri": "/employees/1/charlie-smith",
"rel": "delete",
"method": "DELETE"
},
{
"uri": "/employees/1/charlie-smith",
"rel": "edit",
"method": "PATCH"
}
]
},
"links": [
{
"uri": "/employees",
"rel": "create",
"method": "POST"
}
]
}links在响应中包括JSON字段,使客户端可以访问与新资源和整个应用程序相关的资源,而不必事先知道其URI或方法。