SpringBoot RESTful指南

RESTful API 概述

Rest 是一種規範,符合 Rest 的 Api 就是 Rest Api。簡單地說就是網際網路裝置利用 HTTP 協議透過 GET、POST、DELETE、PUT、PATCH 來操作具有URI標識的伺服器資源,返回統一格式的資源資訊,包括 JSON、XML、CSV、ProtoBuf、其他格式。

1。1 域名

建議使用 api。domain。com

1。2

協議

建議使用https

1。3 版本號

建議放在url裡,

https://api。domain。com/v1

1。4 路徑

在RESTful架構中,每個網址代表一種資源(resource),所以網址中不能有動詞,只能有名詞,而且所用的名詞往往與資料庫的表格名對應。

1。5 http方法

常用的動詞包括了5個

GET(SELECT):從伺服器取出資源(一項或多項)。

POST(CREATE):在伺服器新建一個資源。

PUT(UPDATE):在伺服器更新資源(客戶端提供改變後的完整資源)。

PATCH(UPDATE):在伺服器更新資源(客戶端提供改變的屬性)。

DELETE(DELETE):從伺服器刪除資源。

1。6 過濾資訊

如果記錄數量很多,伺服器不可能都將它們返回給使用者。API應該提供引數,過濾返回結果。

api。domain。com/v1/users?limit=10 :指定返回記錄的數量

api。domain。com/v1/users?offset=10:指定返回記錄的開始位置

api。domain。com/v1/users?page=2&per_page=100:指定第幾頁,以及每頁的記錄數

api。domain。com/v1/users?sortby=name&order=asc:指定返回結果按照哪個屬性排序,以及排序順序

api。domain。com/v1/users?animal_type_id=1:指定篩選條件

1。7 狀態碼

建議使用 HTTP 的狀態碼

200 OK - [GET]:伺服器成功返回使用者請求的資料,該操作是冪等的(Idempotent)。

201 CREATED - [POST/PUT/PATCH]:使用者新建或修改資料成功。

202 Accepted - [*]:表示一個請求已經進入後臺排隊(非同步任務)

204 NO CONTENT - [DELETE]:使用者刪除資料成功。

400 INVALID REQUEST - [POST/PUT/PATCH]:使用者發出的請求有錯誤,伺服器沒有進行新建或修改資料的操作,該操作是冪等的。

401 Unauthorized - [*]:表示使用者沒有許可權(令牌、使用者名稱、密碼錯誤)。

403 Forbidden - [*] 表示使用者得到授權(與401錯誤相對),但是訪問是被禁止的。

404 NOT FOUND - [*]:使用者發出的請求針對的是不存在的記錄,伺服器沒有進行操作,該操作是冪等的。

406 Not Acceptable - [GET]:使用者請求的格式不可得(比如使用者請求JSON格式,但是隻有XML格式)。

410 Gone -[GET]:使用者請求的資源被永久刪除,且不會再得到的。

422 Unprocesable entity - [POST/PUT/PATCH] 當建立一個物件時,發生一個驗證錯誤。

500 INTERNAL SERVER ERROR - [*]:伺服器發生錯誤,使用者將無法判斷髮出的請求是否成功。

1。8 錯誤處理

返回指定錯誤資訊內容

{ “error”:“err message”}

1。9 返回結果

針對不同操作,伺服器向用戶返回的結果應該符合以下規範。

GET /collection:返回資源物件的列表(陣列)

GET /collection/resource:返回單個資源物件

POST /collection:返回新生成的資源物件

PUT /collection/resource:返回完整的資源物件

PATCH /collection/resource:返回完整的資源物件

DELETE /collection/resource:返回一個空文件

2 Spring Boot 中如何使用 RESTful API

本章節需要編寫的是對一個使用者的增刪改查操作,如下表是一個非 RESTful 和 標準 RESTful 的對比表。

Api Name

非RESTful

RESTful Api

獲取使用者

/user/query/1

/users/1 GET

新增使用者

/user/add

/users POST

更新使用者

/user/edit

/users PUT

刪除使用者

/user/delete

/users DELETE

2。1 使用工具

使用spring tool suit 4,以下簡稱sts

2。2 新建專案

file -> new -> spring starter project

SpringBoot RESTful指南

只要選中web模組即可

SpringBoot RESTful指南

2。3 編寫示例程式碼

UserDAO

UserContorller

2。3。1 UserDAO程式碼

定義了user id和 user name 兩個欄位

public class UserDAO { private Integer userId; private String userName; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this。userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this。userName = userName; } }

2。3。2 User controller 程式碼

定義增刪改查4個方法

方法

路徑

說明

POST

http://localhost:8080/users

建立使用者

GET

http://localhost:8080/users

列出所有使用者

PUT

http://localhost:8080/users/{id}

更新使用者

DELETE

http://localhost:8080/users/{id}

刪除使用者

import java。util。ArrayList;import java。util。List;import org。springframework。http。HttpStatus;import org。springframework。web。bind。annotation。DeleteMapping;import org。springframework。web。bind。annotation。GetMapping;import org。springframework。web。bind。annotation。PathVariable;import org。springframework。web。bind。annotation。PostMapping;import org。springframework。web。bind。annotation。PutMapping;import org。springframework。web。bind。annotation。RequestBody;import org。springframework。web。bind。annotation。ResponseStatus;import org。springframework。web。bind。annotation。RestController;import com。example。demo。dao。UserDAO;@RestControllerpublic class UserController { //create a user @PostMapping(“/users”) @ResponseStatus(HttpStatus。CREATED) public Object addUser(@RequestBody UserDAO user) { list。add(user); return user; } // list users @GetMapping(“/users”) @ResponseStatus(HttpStatus。OK) public Object getUsers(){ return list; } //update a user @PutMapping(“/users/{id}”) @ResponseStatus(HttpStatus。CREATED) public Object editUser(@PathVariable(“id”) String id,@RequestBody UserDAO user){ for (UserDAO userDAO:list) { if(id。equals(userDAO。getUserId()。toString())){ list。remove(userDAO); list。add(user); break; } } return user; } //delete a user @DeleteMapping(“/users/{id}”) @ResponseStatus(HttpStatus。NO_CONTENT) public Object deleteUser(@PathVariable(“id”) String id){ UserDAO user=null; for (UserDAO userDAO:list) { if(id。equals(userDAO。getUserId()。toString())){ user=userDAO; list。remove(userDAO); break; } } return user; } private List list=new ArrayList();}

2。4 執行程式碼

選中demo application,run as,spring boot app

啟動內嵌的tomcat,預設埠是8080

SpringBoot RESTful指南

No active profile set, falling back to default profiles: defaultTomcat initialized with port(s): 8080 (http)Starting service [Tomcat]Starting Servlet engine: [Apache Tomcat/9。0。53]Initializing Spring embedded WebApplicationContextRoot WebApplicationContext: initialization completed in 496 msTomcat started on port(s): 8080 (http) with context path ‘’Started DemoApplication in 0。973 seconds (JVM running for 1。402)Initializing Spring DispatcherServlet ‘dispatcherServlet’Initializing Servlet ‘dispatcherServlet’Completed initialization in 1 ms

2。5 使用postman來測試

{ “userId”: 1234, “userName”: “dashu”}

2。5。1 建立一個使用者

SpringBoot RESTful指南

2。5。2 獲取所有使用者

SpringBoot RESTful指南

2。5。3 更新一個使用者

SpringBoot RESTful指南

SpringBoot RESTful指南

2。5。4 刪除一個使用者

SpringBoot RESTful指南

SpringBoot RESTful指南