在現代微服務與前後端分離(Frontend-Backend Separation)的架構中,API 規格書是前端與後端工程師協作的「溝通合約(Contract)」。
如果缺乏一份清晰、標準化的 API 規格,開發過程往往會陷入無止境的溝通消耗:「這個欄位是駝峰命名還是底線?」、「這個時間格式是 ISO-8601 還是毫秒時間戳?」、「這個欄位是必填還是選填?」。
手寫一份完整的 OpenAPI 3.0 (Swagger) 規格或 JSON Schema 通常非常繁瑣,需要撰寫大量縮排嚴格的 YAML 或巢狀 JSON。今天我們就來示範:如何讓 ChatGPT 扮演 API 架構師,只需輸入 Java DTO 或簡單欄位清單,就能一鍵生成標準的 OpenAPI 3.0 與 JSON Schema 規格!
想要讓 AI 產出可直接貼進 Swagger Editor 且無語法錯誤的規格書,請使用以下精準模板:
【API 規格生成提示詞範本】
請扮演資深 API 架構師。請根據我提供的資料結構與業務場景,產出標準的 OpenAPI 3.0.3 (YAML 格式) 與 JSON Schema。
業務場景:[例如:建立新會員資料接口 POST /api/v1/users]
傳入資料結構(Java DTO / 欄位清單):
[貼上 DTO 代碼或欄位說明]
生成要求如下:
假設我們後端定義了如下的註冊資料結構(Java Record):
[後端 Java 資料結構]
public record CreateUserRequest(
String username,
String email,
String password,
String mobile,
Integer age
) {}
**商業約束**:
* `username`:長度 4~20 字元,必填。
* `email`:符合標準 Email 格式,必填。
* `password`:長度 8~32 字元,敏感欄位。
* `mobile`:台灣手機號碼格式(09 開頭 10 碼),非必填。
* `age`:數值範圍 1~120,非必填。
將需求交給 AI 後,生成的 YAML 結構精確且階層分明,可直接載入 Swagger UI 呈現互動文件:
[OpenAPI 3.0.3 YAML 規格]
openapi: 3.0.3
info:
title: User Management Service API
version: 1.0.0
description: 提供會員註冊與帳號管理相關端點
paths:
/api/v1/users:
post:
summary: 建立新會員帳號
operationId: createUser
tags:
- Users
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: 會員建立成功
content:
application/json:
schema:
type: object
properties:
userId:
type: string
format: uuid
example: "550e8400-e29b-41d4-a716-446655440000"
message:
type: string
example: "會員註冊成功"
'400':
description: 傳入參數格式不符合驗證規範
components:
schemas:
CreateUserRequest:
type: object
required:
- username
- email
- password
properties:
username:
type: string
minLength: 4
maxLength: 20
description: 會員帳號名稱
example: "anson_chung"
email:
type: string
format: email
description: 電子郵件信箱
example: "anson@example.com"
password:
type: string
format: password
minLength: 8
maxLength: 32
description: 密碼字串
example: "P@ssw0rd2026"
mobile:
type: string
pattern: '^09\d{8}$'
description: 台灣手機號碼 (10碼數字)
example: "0912345678"
age:
type: integer
minimum: 1
maximum: 120
description: 年齡
example: 20
除了整份 API 規格,前端在表單驗證(例如使用 Ajv 等校驗庫)時,常需要獨立的 JSON Schema。AI 也能一鍵提煉出來:
[獨立 JSON Schema 定義]
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "CreateUserRequestSchema",
"type": "object",
"required": ["username", "email", "password"],
"properties": {
"username": {
"type": "string",
"minLength": 4,
"maxLength": 20
},
"email": {
"type": "string",
"format": "email"
},
"password": {
"type": "string",
"minLength": 8,
"maxLength": 32
},
"mobile": {
"type": "string",
"pattern": "^09\\d{8}$"
},
"age": {
"type": "integer",
"minimum": 1,
"maximum": 120
}
},
"additionalProperties": false
}
additionalProperties: false:additionalProperties: false,能有效防止惡意使用者傳入非預期的欄位,展現出良好的安全防禦意識。今天我們掌握了利用 AI 快速將 Java 資料結構轉譯為標準 OpenAPI (Swagger) YAML 與 JSON Schema 的方法,讓繁重的合約規格書撰寫變得輕鬆無比。