博客网站 REST API 设计
假设有一个博客网站 https://blog.com
,它通过 https://api.blog.com
接收 REST API 请求,现在需要为其设计 REST API。
获取某个用户的博客列表(无需认证)
请求:
GET https://api.blog.com/users/:username/posts
参数 | 类型 | 描述 |
---|---|---|
type | stirng | 列表项的类型,包括 all (默认)、post_id 、post_title 、published 和 updated 。 |
如果请求成功,服务器返回 HTTP 200 OK
状态码以及内容:
{
"kind": "#postList",
"username": "cat",
"posts": [
{
"post_id": "1",
"post_title": "Post 1 Title",
"published": "2019-08-02T06:00:00",
"updated": "2019-08-03T06:00:00"
},
{
"post_id": "2",
"post_title": "Post 2 Title",
"published": "2019-10-02T06:00:00",
"updated": "2019-10-04T06:00:00"
}
// ...
]
}
查看某篇博客(无需认证)
请求:
GET https://api.blog.com/posts/:post_id
如果请求成功,服务器返回 HTTP 200 OK
状态码以及内容:
{
"kind": "#post",
"username": "Tom",
"post_id": "55",
"post_title": "Blog 55 Title",
"published": "2019-11-02T06:00:00",
"updated": "2019-12-05T06:00:00",
"post_content": "Blog 55 Content"
}
查看某篇博客的评论(无需认证)
请求:
GET https://api.blog.com/posts/:post_id/comments
如果请求成功,服务器返回 HTTP 200 OK
状态码以及内容:
{
"kind": "#commentList",
"post_id": "123",
"comments" : [
{
"comment_id": "12413253452346",
"username": "user1",
"published": "2019-11-10T06:00:00",
"content": "comment 1"
},
{
"comment_id": "12413253452388",
"username": "user2",
"published": "2019-11-10T013:00:00",
"content": "comment 2"
}
// ...
]
}
创建一篇博客(需要认证)
请求:
POST https://api.blog.com/posts
Authorization: /* OAuth 2.0 token here */
Content-Type: application/json
{
"kind": "#post",
"post_title": "your post title",
"post_content": "your post content"
}
如果请求成功,服务器返回 HTTP 201 Created
状态码以及内容:
{
"kind": "#post",
"username": "Matt",
"post_id": "123",
"post_title": "your post title",
"published": "2019-11-22T06:00:00",
"updated": "2019-11-22T06:00:00",
"post_content": "your post content"
}
更新某篇博客(需要认证)
请求:
PUT https://api.blog.com/posts/:post_id
Authorization: /* OAuth 2.0 token here */
Content-Type: application/json
{
"kind": "#post",
"post_id": "your post id"
"post_title": "your post title",
"post_content": "your post content"
}
如果请求成功,服务器返回 HTTP 200 OK
状态码以及内容:
{
"kind": "#post",
"username": "Matt",
"post_id": "123",
"post_title": "your post title",
"published": "2019-11-22T06:00:00",
"updated": "2019-12-23T06:00:00",
"post_content": "your post content"
}
删除某篇博客(需要认证)
请求:
DELETE https://api.blog.com/posts/:post_id
Authorization: /* OAuth 2.0 token here */
如果请求成功,服务器返回 HTTP 204 No Content
状态码。