文章目錄
作業要求
模仿 Github,設計一個博客網站的 API
參考網址及博客
REST簡介
在 2000 年,Roy Fielding 提議使用表述性狀態轉移 (REST) 作爲設計 Web 服務的體系性方法。 REST 是一種基於超媒體構建分佈式系統的架構風格。 REST 獨立於任何基礎協議,並且不一定綁定到 HTTP。 但是,最常見的 REST 實現使用 HTTP 作爲應用程序協議。
基於 HTTP 的 REST 的主要優勢在於它使用開放標準,不會綁定 API 的實現,也不會將客戶端應用程序綁定到任何具體實現。
具體實現
博客網址
假設該博客網址爲:https://api.testblog.com
一、登陸
- 命令
curl -u username -p password https://api.testblog.com
- 結果
返回的狀態碼 | 對應結果 |
---|---|
2xx | 請求成功 |
4xx | 請求異常 |
- 可能的幾種錯誤:
返回的狀態碼 | 對應錯誤 |
---|---|
401 | 密碼不正確 |
403 | 訪問過於頻繁 |
404 | 賬戶不存在 |
- 例如403
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Connection: close
{
"message": "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later.",
"documentation_url": "https://api.testBlog/#abuse-rate-limits"
}
二、請求資源
通過GET命令請求資源,返回JSON格式的數據。
1. 查看用戶的所有博客基本信息
curl -i "https://api.testblog.com/username"
2. 查看用戶的個人信息:
curl -i "https://api.testblog.com/username/info"
3. 查看評論
curl -i "https://api.testblog.com/username/articlename/comment"
4. 查找博客
curl -i "https://api.testblog.com/username/search?key=yourkeyword"
三、新建資源
通過POST命令新建一個資源
1. 發佈新博客
curl -i "https://api.testblog.com/username/new" -d "{"title":"yourtitle","content":"yourcontent","date":"date"}"
2. 發佈新評論
curl -c "your_comments" "https://api.testblog.com/username/articlename/comment/new"
替換資源
通過PUT命令替換一個資源,需上傳更新後的博客內容和所在頁面。
1. 更新博客
curl -i "https://api.testblog.com/username/articlename/update" -d "{"title":"yourtitle","content":"yourcontent","date":"date"}"
2. 更新評論
curl -c "your_comments" "https://api.testblog.com/username/articlename/comment/update"
刪除資源
利用DELETE命令在服務器刪除一個資源。
1. 刪除博客
curl -i "https://api.testblog.com/username/articlename/delete"