假设我有一个REST端点,允许客户POST
新Article
。其网址为http://api.example.com/articles。我还有一个终点,他们可以GET
之前发布的Article
。其网址为http://api.example.com/articles/ {articleId}
文章的状态表示是这样的。
{
"title": "Some title",
"body": "Article body"
}
原始POST
请求: -
POST http://api.example.com/articles HTTP/1.1
Content-Type: application/vnd.example.com.article+json
Host: api.example.com
Content-Length: 76
{
"title": "Some title",
"body": "Article body"
}
原始GET
请求: -
GET http://api.example.com/articles/dfgh HTTP/1.1
Accept: application/vnd.example.com.article+json
Host: api.example.com
现在我花时间提供JSON Schema架构来描述我的文章状态表示。托管于http://spec.api.example.com/article.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"title": {
"type": "string"
},
"body": {
"type": "string"
}
},
"required": [
"title",
"body"
]
}
为此类GET
和POST
个请求向客户提供此文档的最佳做法是什么?
答案 0 :(得分:2)
记录如何发出请求的最佳方式是使用某种超媒体格式来表达它。我个人的偏好是JSON Hyper-Schema,因为你已经在使用JSON Schema,所以它很自然。
创建文章的链接看起来像这样。
{
"rel": "create",
"href": "/articles",
"method": "post",
"schema": { "$ref": "http://spec.api.example.com/article.json" }
}
因此,下一步是确定如何公开此链接描述对象(LDO)。答案取决于您的API的流程,但这里有几个常见的选项。
API的入口点
GET http://api.example.com/
HTTP/1.1 200 OK
Link: <http://spec.api.example.com/index.json>; rel=describedby
...
GET http://spec.api.example.com/index.json
HTTP/1.1 200 OK
{
"links": [
{
"rel": "create",
"href": "/articles",
"method": "post",
"schema": { "$ref": "http://spec.api.example.com/article.json" }
}
]
}
文章列出资源
GET http://api.example.com/articles
HTTP/1.1 200 OK
Link: <http://spec.api.example.com/articles.json>; rel=describedby
[
{
"title": "Some title",
"body": "Article body"
},
{
"title": "Another title",
"body": "Article body"
}
]
GET http://spec.api.example.com/articles.json
HTTP/1.1 200 OK
{
"type": "array",
"items": { "$ref": "http://spec.api.example.com/article.json" },
"links": [
{
"rel": "create",
"href": "/articles",
"method": "post",
"schema": { "$ref": "http://spec.api.example.com/article.json" }
}
]
}
答案 1 :(得分:0)