服務計算作業:REST API 設計
框架模式
- 所有的API都是遵循HTTPS規定的,從https://api.blog.com中獲取,所有的傳輸數據都是json格式。
- 有GET, PUT, POST, DELETE方法
- 網絡狀態碼遵循HTTPS要求,比如
400 (bad request)- 指代壞請求(如,參數錯誤)
200(OK) - 表示已在響應中發出
404 (not found)- 資源不存在
500 (internal server error)- 通用錯誤響應
API的url設計
可以通過
curl https://api.github.com
查看所有的API url,得到類似如下信息,比如user_url代表用戶信息,article_url代表用戶的全部文章
{
"user_url": "https://api.blog.com/users/{user}",
"article_url":"https://api.blog.com//{user}articles",
...
}
登錄
運行curl -u "username" https://exampleblog.com
,然後會要求輸入password,只要用戶名和密碼都正確即可登錄成功。也可以通過下面這種形式登錄
curl -i https://api.github.com -u valid_username:valid_password
例如:
curl -u Alvoboke https://blog.csdn.net/
Enter host password for user 'Alvoboke':
<!DOCTYPE html>
<html>
<head>
...
查看所有文章
命令:GET /:username/articles
可以通過curl執行查看一下,
curl -u Alvoboke https://blog.csdn.net/Aivoboke/articles
Enter host password for user 'Alvoboke':
<!DOCTYPE html>
<html>
<head>
查看某篇文章
GET /:username/articles/{id}
比如
curl -u -i https://blog.csdn.net/Aivoboke/articles/78882941
Status:200 OK
--------------------------
{
"total_count": 40,
"items": [
{
"articleID": 3081286,
"name": "自頂向下設計C語言貪喫蛇",
"owner": {
"name": "Aivoboke",
"id": 123,
"url": "https://blog.csdn.net/Alvoboke/",
"type": "User"
},
"article_url": "https://blog.csdn.net/Alvoboke/article/details/78882941"
"private": false,
"description": "...",
"reading number": 0,
"created_at": "2019-11-21T18:31:50Z",
"updated_at": "2019-11-21T18:31:50Z",
"words": 10265,
"language": "Chinese",
"content":"<!DOCTYPE html>...."
},
...
]
}
搜索文章
GET /:username/search/articles/?{id}{name}
其中id是指文章唯一編號,name是文章標題
發佈文章
發佈文章是爲網站添加內容,所以使用PUT語句
PUT /:user/publish/article/{id}
Status : 200 OK
-----------------------
{
"isPublished":true ,
"article":{
"articleID": 78882941,
"name": "自頂向下設計C語言貪喫蛇",
"owner": {
"name": "Aivoboke",
"id": 35728473,
"url": "https://blog.csdn.net/Alvoboke/",
"type": "User"
},
"article_url": "https://blog.csdn.net/Alvoboke/article/details/78882941"
"private": false,
"description": "...",
"reading number": 0,
"created_at": "2019-11-21T18:31:50Z",
"updated_at": "2019-11-21T18:31:50Z",
"words": 10265,
"language": "Chinese",
"content":"<!DOCTYPE html>...."
},
刪除文章
使用DELETE方法,需要登錄並指明文章id,
DELETE /:user/articles/delete/{id}
curl -u -i https://blog.csdn.net/Aivoboke/articles/delete/78882941
Status : 200 OK
-----------------------
{
"isDeleted":true / false,
"id" : 10
}
創建評論
POST /:user/article/{id}/comment
例如:
curl -i -u https://blog.csdn.net/Aivoboke/article/78882941/comments -d {"content":"my personal comment"}
{
"id": 78882941,
"author": "Aivoboke",
"url": "xx",
"contents":xx,
"user":{
"name": "Aivoboke",
"id": 35728473,
"url": "user blog url",
"type": "User"
}
"created_at": "2019-11-21T18:23:56Z",
}