# 什麼是Fake API? &nbsp;&nbsp;簡單來說,Fake API 就是一個「假的」API,用來模擬真實 API 的行為。 &nbsp;&nbsp;為什麼需要 Fake API 呢?在現代開發中,API 串接已經非常常見,但不可能每個團隊都同時完成完整後端開發。因此,當兩個團隊尚未完成合約或正式 API 開發時,Fake API 可以用來: 1. 讓前端或第三方開發者能先行測試串接。 2. 方便雙方對 API 格式、資料結構進行對測。 3. 練習或展示系統功能,而不依賴真實資料庫或完整後端。 ### 實作 &nbsp;&nbsp;假設我們需要串接對方提供的 API,並已知道 API 欄位名稱與型別。我們可以先建立 Fake API 來模擬回應。 Controller ```java= @RestController @RequestMapping("/api/users") public class UserController { // 模擬一個 GET API 取得所有使用者 @GetMapping public List<UserResponse> getAllUsers() { List<UserResponse> users = new ArrayList<>(); users.add(new UserResponse(1L, "Alice", "alice@example.com")); users.add(new UserResponse(2L, "Bob", "bob@example.com")); return users; } // 模擬一個 POST API 建立使用者 @PostMapping public UserResponse createUser(@RequestBody UserRequest request) { // 直接回傳請求內容,模擬建立成功 return new UserResponse(999L, request.getName(), request.getEmail()); } // 模擬一個 GET API 取得單一使用者 @GetMapping("/{id}") public UserResponse getUserById(@PathVariable Long id) { // 直接返回假資料 return new UserResponse(id, "FakeUser" + id, "fake" + id + "@example.com"); } } ``` Response ```java= @Getter @Builder public class UserResponse { private Long id; private String name; private String email; } ``` Resquest ```java= @Getter public class UserRequest { private String name; private String email; } ``` http - GET 所有使用者 ```java= GET /api/users Response: [ { "id": 1, "name": "Alice", "email": "alice@example.com" }, { "id": 2, "name": "Bob", "email": "bob@example.com" } ] ``` http - GET 單一使用者 ```java= GET /api/users/10 Response: { "id": 10, "name": "FakeUser10", "email": "fake10@example.com" } ``` http - POST 建立使用者 ```java= POST /api/users Request Body: { "name": "Charlie", "email": "charlie@example.com" } Response: { "id": 999, "name": "Charlie", "email": "charlie@example.com" } ``` ### 流程圖 ``` +-----------------+ GET / POST +----------------------+ | | -----------------------> | | | 前端 Frontend | | Fake API Controller | | | <----------------------- | | +-----------------+ 回傳模擬資料 +----------------------+ | | | | | | | | v v +-----------------+ +----------------------+ | | | | | 顯示回應資料 UI | | 模擬 API 行為 | | | | - GET all users | +-----------------+ | - GET user by ID | | - POST create user | +----------------------+ ``` :::info 說明: 1. 前端發送 GET/POST 請求給 Fake API Controller。 2. Controller 根據請求回傳模擬資料。 3. 前端接收回應並顯示在 UI 上。 4. Controller 內部可以模擬不同 API,例如: * `GET /users` → 回傳多個使用者 * `GET /users/{id}` → 回傳單一使用者 * `POST /users` → 模擬建立使用者 ::: ### 總結 &nbsp;&nbsp;Fake API 非常適合: 1. 快速展示功能或練習 API 串接。 2. 在不需要開發完整後端(Service、DB)的情況下,驗證前端或第三方系統。 3. 只需要完成 Controller 層,即可模擬對外 API 行為。