API 規格文件範本(API Specification Document)

參照標準:OpenAPI Specification 3.1(OAS 3.1)/ Linux Foundation 標準

文件用途:定義 RESTful API 的端點、請求/回應格式、認證機制與錯誤處理規範

適用階段:系統設計階段(Detail Design Phase)

範本版本:v2.0(2026-10-06)|對應《軟體開發標準程序教學手冊》v2.0 第 4.3 節


📋 章節目錄

  1. 文件資訊
  2. API 概述
  3. 認證與授權
  4. 共用規範
  5. 端點定義
  6. 資料模型
  7. 錯誤處理
  8. 版本策略
  9. OpenAPI 規格檔
  10. 附錄
  11. 審查與驗證

1. 文件資訊

📝 範本

項目內容
文件編號API-{專案代碼}-{序號}
API 名稱{系統名稱} API
API 版本v{主版本}
文件版本v{主版本}.{次版本}
狀態草稿 / 審核中 / 已發布
建立日期{YYYY-MM-DD}
最後更新{YYYY-MM-DD}
負責人{姓名/角色}
Base URLhttps://{domain}/api/v{version}

📖 使用說明

  • API 版本與文件版本分開管理:API 版本影響端點路徑,文件版本追蹤文件修訂
  • Base URL 需區分環境(DEV/SIT/UAT/PROD)
  • 依據 OpenAPI 3.1 info 物件結構設計

💡 範例

項目內容
文件編號API-HRM-001
API 名稱HRMS API
API 版本v1
Base URLhttps://api.company.com/hrms/v1

2. API 概述

📝 範本

2.1 API 目的

{描述此 API 提供的服務範圍與主要功能}

2.2 目標使用者

使用者類型說明權限範圍
{類型}{說明}{可存取的資源}

2.3 API 資源總覽

資源(Resource)Base Path說明支援操作
{資源名稱}/{resource}{描述}GET, POST, PUT, DELETE

📖 使用說明

  • API 設計遵循 REST 架構風格,以資源(Resource)為中心
  • 資源命名使用複數名詞(如 /employees,非 /employee)
  • 使用者類型對應不同的 OAuth Scope 或角色

💡 範例

2.3 API 資源總覽

資源Base Path說明支援操作
Employees/employees員工基本資料管理GET, POST, PUT, PATCH
Leaves/leaves請假申請與管理GET, POST, PUT, DELETE
Payrolls/payrolls薪資記錄查詢GET
Departments/departments部門組織管理GET, POST, PUT

3. 認證與授權

📝 範本

3.1 認證機制

項目規格
認證方式{OAuth 2.0 / API Key / Bearer Token}
Token 格式{JWT / Opaque}
Token 位置{Authorization Header / Cookie}
Token 有效期{時間}
刷新機制{Refresh Token / Re-authenticate}

3.2 授權模型

Scope / Role描述可存取資源
{scope}{描述}{資源清單}

3.3 請求範例

GET /api/v1/employees HTTP/1.1
Host: api.company.com
Authorization: Bearer {access_token}
Content-Type: application/json

📖 使用說明

  • 依據 OAuth 2.0 RFC 6749 與 OpenAPI 3.1 Security Scheme 規範
  • Token 必須透過 HTTPS 傳輸,禁止在 URL Query Parameter 中傳遞
  • API Key 適用於 Server-to-Server 場景,使用者互動場景建議 OAuth 2.0

💡 範例

3.1 認證機制

項目規格
認證方式OAuth 2.0 Authorization Code Flow(使用者)/ Client Credentials(系統)
Token 格式JWT(RS256 簽章)
Token 位置Authorization: Bearer {token}
Token 有效期Access Token: 15 分鐘 / Refresh Token: 7 天

3.2 授權模型

Scope描述可存取資源
employee:read讀取員工資料GET /employees
employee:write修改員工資料POST/PUT /employees
leave:manage管理假勤(含審核)ALL /leaves
payroll:read查詢薪資GET /payrolls

4. 共用規範

📝 範本

4.1 HTTP 方法語義

方法語義冪等性安全性
GET讀取資源是是
POST建立資源否否
PUT完整更新資源是否
PATCH部分更新資源否否
DELETE刪除資源是否

4.2 分頁規範

{
  "data": [ { "id": "{資源 ID}" } ],
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "totalPages": 5,
    "totalCount": 98
  }
}

分頁參數:

參數型別預設值說明
pageinteger1頁碼(從 1 開始)
pageSizeinteger20每頁筆數(最大 100)
sortstring-排序欄位(如 createdAt:desc)

4.3 日期時間格式

格式標準範例
日期時間ISO 8601 / RFC 33392026-05-18T10:30:00+08:00
純日期ISO 86012026-05-18
時區UTC 偏移量+08:00

4.4 共用 HTTP Headers

Header用途必填範例
Content-Type請求/回應格式是application/json
Accept期望回應格式否application/json
X-Request-Id請求追蹤 ID是uuid-v4
X-Correlation-Id跨服務追蹤 ID否uuid-v4

📖 使用說明

  • 分頁設計避免一次回傳過多資料,保護伺服器效能
  • 日期時間一律使用 ISO 8601 格式,避免時區混亂
  • X-Request-Id 用於日誌追蹤與問題排查,建議每個請求必帶
  • 所有字串使用 UTF-8 編碼

💡 範例

請求假勤清單(含分頁與排序):

GET /api/v1/leaves?page=2&pageSize=10&sort=startDate:desc HTTP/1.1
Host: api.company.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
X-Request-Id: 550e8400-e29b-41d4-a716-446655440000
Accept: application/json

5. 端點定義

📝 範本

5.1 {資源名稱}

{HTTP Method} /{path}

描述:{端點功能描述}

路徑參數(Path Parameters):

參數型別必填說明
{param}{type}是/否{描述}

查詢參數(Query Parameters):

參數型別必填預設值說明
{param}{type}是/否{default}{描述}

請求 Body(Request Body):

{
  "field1": "{type} - {描述}",
  "field2": "{type} - {描述}"
}

回應(Response):

HTTP Status說明回應 Body
200 OK成功{回應結構}
201 Created建立成功{回應結構}
400 Bad Request參數錯誤Problem Details(application/problem+json)
401 Unauthorized未認證Problem Details(application/problem+json)
403 Forbidden無權限Problem Details(application/problem+json)
404 Not Found資源不存在Problem Details(application/problem+json)

回應 Body 範例:

{
  "data": { "id": "{資源 ID}" },
  "meta": {
    "requestId": "{uuid}",
    "timestamp": "{ISO-8601 含時區}"
  }
}

📖 使用說明

  • 每個端點需定義:路徑、方法、參數、請求體、回應碼、回應體
  • 路徑參數使用 {id} 格式,代表資源唯一識別碼
  • 回應結構統一使用 { data, meta, errors } 信封格式
  • 列出所有可能的 HTTP Status Code,包含錯誤場景

💡 範例

5.1 假勤管理(Leaves)

POST /leaves

描述:員工提交請假申請

請求 Body:

{
  "leaveType": "annual",
  "startDate": "2026-06-01",
  "endDate": "2026-06-03",
  "reason": "家庭旅遊",
  "delegateId": "E20260015"
}
欄位型別必填說明
leaveTypestring是假別代碼(annual/sick/personal/official)
startDatestring(date)是請假起始日
endDatestring(date)是請假結束日
reasonstring是請假事由(最長 500 字)
delegateIdstring否職務代理人員工編號

回應:

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/leaves/LV-20260601-001

{
  "data": {
    "id": "LV-20260601-001",
    "employeeId": "E20260001",
    "leaveType": "annual",
    "startDate": "2026-06-01",
    "endDate": "2026-06-03",
    "days": 3,
    "status": "pending",
    "createdAt": "2026-05-18T10:30:00+08:00"
  },
  "meta": {
    "requestId": "550e8400-e29b-41d4-a716-446655440000",
    "timestamp": "2026-05-18T10:30:00+08:00"
  }
}
GET /leaves/{id}

描述:查詢單筆請假紀錄

路徑參數:

參數型別必填說明
idstring是請假單編號

回應:

HTTP Status說明
200 OK回傳請假紀錄
404 Not Found請假單不存在

6. 資料模型(Schemas)

📝 範本

6.1 {Schema 名稱}

欄位型別必填說明驗證規則
{field}{type}是/否{描述}{min/max/pattern/enum}

6.2 列舉值(Enums)

Enum 名稱值說明
{EnumName}value1{描述}
value2{描述}

📖 使用說明

  • Schema 定義可重複使用的資料結構(對應 OpenAPI components/schemas)
  • 每個欄位需定義型別、必填性、驗證規則
  • 列舉值需完整列出所有合法值

💡 範例

6.1 LeaveRequest Schema

欄位型別必填說明驗證規則
leaveTypestring是假別enum: annual, sick, personal, official
startDatestring(date)是起始日format: date, ≥ today
endDatestring(date)是結束日format: date, ≥ startDate
reasonstring是事由minLength: 1, maxLength: 500
delegateIdstring否代理人pattern: ^E\d{8}$

6.2 LeaveStatus Enum

值說明
pending待審核
approved已核准
rejected已駁回
cancelled已取消

7. 錯誤處理

📝 範本

7.1 錯誤回應格式(RFC 9457 Problem Details)

錯誤回應的 Content-Type 為 application/problem+json。type、title、status、detail、instance 為 RFC 9457 標準欄位;code、traceId、errors 為企業擴充欄位。

{
  "type": "https://{domain}/problems/{problem-type}",
  "title": "{錯誤類型的簡短說明,同一 type 固定不變}",
  "status": 400,
  "detail": "{此次錯誤的具體說明}",
  "instance": "{發生錯誤的請求路徑}",
  "code": "{ERROR_CODE}",
  "traceId": "{W3C Trace Context 的 trace-id,32 位十六進位}",
  "errors": [
    { "pointer": "#/{欄位路徑}", "detail": "{欄位錯誤說明}" }
  ]
}

7.2 錯誤代碼清單

HTTP StatusError CodeProblem type(URI 結尾)說明處理建議
400VALIDATION_ERRORvalidation-error請求參數驗證失敗依 errors[].pointer 修正後重試
400INVALID_DATE_RANGEinvalid-date-range日期範圍無效確認 endDate ≥ startDate
401TOKEN_EXPIREDtoken-expiredToken 已過期使用 Refresh Token 取得新 Token
401INVALID_TOKENinvalid-tokenToken 無效重新登入取得 Token
403INSUFFICIENT_SCOPEinsufficient-scope權限不足確認帳號具有對應 Scope
404RESOURCE_NOT_FOUNDresource-not-found資源不存在(或無權查看)確認 ID 是否正確
409CONFLICTconflict資源狀態衝突取得最新版本後重試
422BUSINESS_RULE_VIOLATIONbusiness-rule-violation格式正確但違反業務規則(Unprocessable Content)參考 detail 說明
429RATE_LIMIT_EXCEEDEDrate-limit-exceeded超過請求頻率限制依 Retry-After 標頭等待後重試
500INTERNAL_ERRORinternal-error伺服器內部錯誤提供 traceId 聯繫技術支援

7.3 Rate Limiting

項目規格
限制方式{Per User / Per API Key / Per IP}
限制量{N} requests / {時間單位}
超限回應429 Too Many Requests + Retry-After 標頭(RFC 9110)
額度標頭{X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset(業界慣例,非標準)}

📖 使用說明

  • 錯誤格式必須遵循 RFC 9457 Problem Details(RFC 9457 已取代 RFC 7807),對應《軟體開發標準程序教學手冊》4.3
  • 同一種錯誤固定使用同一個 type URI 與 title;detail 才描述個案
  • Error Code 使用大寫蛇形命名(UPPER_SNAKE_CASE),作為企業擴充欄位
  • 422 的名稱依 RFC 9110 為 Unprocessable Content(舊名 Unprocessable Entity)
  • 錯誤訊息不得洩漏系統內部資訊(如 Stack Trace、SQL、主機名稱)
  • 標準化的 RateLimit 標頭目前仍為 IETF 草案;使用 X-RateLimit-* 時需在本文件註明語意

💡 範例

POST /api/v1/leaves 申請特休 3 天、但剩餘額度僅 2 天時的回應:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.company.com/problems/business-rule-violation",
  "title": "違反業務規則",
  "status": 422,
  "detail": "申請 3 天特休假,但剩餘假額僅 2 天",
  "instance": "/api/v1/leaves",
  "code": "BUSINESS_RULE_VIOLATION",
  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
  "errors": [
    { "pointer": "#/leaveType", "detail": "特休假剩餘額度 2 天,不足申請天數 3 天" }
  ]
}

8. 版本策略

📝 範本

8.1 版本管理規則

項目策略
版本格式{URL Path / Header / Query Parameter}
版本命名v{major}(如 v1, v2)
向後相容{相容性保證描述}
棄用通知{提前 N 個月通知;回應加上 Deprecation(RFC 9745)與 Sunset(RFC 8594)標頭}
並行支援{同時支援 N 個版本}

8.2 Breaking Change 定義

以下變更視為 Breaking Change(需升版):

  • {Breaking Change 類型 1}
  • {Breaking Change 類型 2}

以下變更為 Non-Breaking(不需升版):

  • {Non-Breaking Change 類型 1}
  • {Non-Breaking Change 類型 2}

📖 使用說明

  • URL Path 版本管理(如 /api/v1/)最直觀,業界最常見
  • Breaking Change:移除或改名欄位、更改欄位型別、新增必填請求欄位、更改行為語意
  • Non-Breaking Change:新增選填欄位、新增端點、新增回應欄位(消費端必須忽略未知欄位)
  • 棄用中的 API 以標頭預告,讓消費端能用程式偵測,而不是只靠公告信

💡 範例

8.1 版本管理規則

項目策略
版本格式URL Path(/api/v1/...)
版本命名v1, v2(Major 版本)
向後相容同一 Major 版本內保證向後相容
棄用通知v2 發布當天起,v1 回應加上 Deprecation: @1798732800(2027-01-01)與 Sunset: Fri, 31 Dec 2027 23:59:59 GMT;舊版本至少維護 12 個月
並行支援最多同時維護 2 個 Major 版本

9. OpenAPI 規格檔

📝 範本

以下為本 API 的 OpenAPI 3.1 規格定義(OpenAPI 3.2.0 已於 2025-09 發布,工具鏈支援後可升級):

openapi: 3.1.0
info:
  title: "{API 名稱}"
  description: "{API 描述}"
  version: "{版本}"
  contact:
    name: "{團隊名稱}"
    email: "{聯絡信箱}"

servers:
  - url: https://{domain}
    description: "Production"
  - url: https://dev-{domain}
    description: "Development"

security:
  - bearerAuth: []

tags:
  - name: "{Tag}"
    description: "{Tag 說明}"

paths:
  /api/v1/{resource}:
    get:
      summary: "{描述}"
      description: "{詳細說明}"
      operationId: "{operationId}"
      tags:
        - "{Tag}"
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
            minimum: 1
        - name: pageSize
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
      responses:
        '200':
          description: "Success"
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/{ResponseSchema}'
        '400':
          $ref: '#/components/responses/Problem'
    post:
      summary: "{描述}"
      description: "{詳細說明}"
      operationId: "{operationId}"
      tags:
        - "{Tag}"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/{RequestSchema}'
      responses:
        '201':
          description: "Created"
        '400':
          $ref: '#/components/responses/Problem'
        '422':
          $ref: '#/components/responses/Problem'

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

  responses:
    Problem:
      description: "錯誤(RFC 9457 Problem Details)"
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Problem'

  schemas:
    Problem:
      type: object
      required: [type, title, status]
      properties:
        type:
          type: string
          format: uri
        title:
          type: string
        status:
          type: integer
        detail:
          type: string
        instance:
          type: string
        code:
          type: string
        traceId:
          type: string
        errors:
          type: array
          items:
            type: object
            properties:
              pointer:
                type: string
              detail:
                type: string

📖 使用說明

  • OpenAPI 3.1 規格檔可直接用於自動生成 API 文件(如 Swagger UI、Redoc)
  • 規格檔納入版本控制,與程式碼同一個 PR 更新(Docs-as-Code)
  • CI 以 Spectral 檢查規格(npx @stoplight/spectral-cli lint openapi.yaml --fail-severity=warn),並以契約測試驗證實作與規格一致
  • $ref 用於引用可重複使用的 Schema 與 Response,避免重複定義;所有被引用的元件都必須定義,否則 lint 會失敗
  • 範本中的 {...} 佔位符必須全部替換後才能通過 lint

💡 範例

以下範例可直接通過 spectral:oas 規則集(--fail-severity=warn)檢查:

openapi: 3.1.0
info:
  title: "HRMS API"
  description: "人力資源管理系統 API"
  version: "1.0.0"
  contact:
    name: "HRMS Development Team"
    email: "hrms-dev@company.com"

servers:
  - url: https://api.company.com/hrms
    description: "Production"
  - url: https://dev-api.company.com/hrms
    description: "Development"

security:
  - bearerAuth: []

tags:
  - name: Leaves
    description: "請假管理"

paths:
  /api/v1/leaves:
    post:
      summary: "提交請假申請"
      description: "員工提交請假申請;假別額度不足時回傳 422。"
      operationId: "createLeave"
      tags:
        - Leaves
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LeaveRequest'
      responses:
        '201':
          description: "請假申請建立成功"
          headers:
            Location:
              description: "新建立的請假紀錄 URL"
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LeaveResponse'
        '400':
          $ref: '#/components/responses/Problem'
        '422':
          $ref: '#/components/responses/Problem'

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

  responses:
    Problem:
      description: "錯誤(RFC 9457 Problem Details)"
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Problem'

  schemas:
    LeaveRequest:
      type: object
      required: [leaveType, startDate, endDate, reason]
      properties:
        leaveType:
          $ref: '#/components/schemas/LeaveType'
        startDate:
          type: string
          format: date
        endDate:
          type: string
          format: date
        reason:
          type: string
          minLength: 1
          maxLength: 500
        delegateId:
          type: string
          pattern: '^E\d{8}$'
    LeaveType:
      type: string
      enum: [annual, sick, personal, official]
    LeaveStatus:
      type: string
      enum: [pending, approved, rejected, cancelled]
    Leave:
      type: object
      required: [id, employeeId, leaveType, startDate, endDate, days, status, createdAt]
      properties:
        id:
          type: string
        employeeId:
          type: string
        leaveType:
          $ref: '#/components/schemas/LeaveType'
        startDate:
          type: string
          format: date
        endDate:
          type: string
          format: date
        days:
          type: number
        status:
          $ref: '#/components/schemas/LeaveStatus'
        createdAt:
          type: string
          format: date-time
    Meta:
      type: object
      properties:
        requestId:
          type: string
          format: uuid
        timestamp:
          type: string
          format: date-time
    LeaveResponse:
      type: object
      required: [data]
      properties:
        data:
          $ref: '#/components/schemas/Leave'
        meta:
          $ref: '#/components/schemas/Meta'
    Problem:
      type: object
      required: [type, title, status]
      properties:
        type:
          type: string
          format: uri
        title:
          type: string
        status:
          type: integer
        detail:
          type: string
        instance:
          type: string
        code:
          type: string
        traceId:
          type: string
        errors:
          type: array
          items:
            type: object
            properties:
              pointer:
                type: string
              detail:
                type: string

10. 附錄

📝 範本

10.1 環境 URL 對照

環境Base URL說明
DEVhttps://dev-api.{domain}/api/v1開發環境
SIThttps://sit-api.{domain}/api/v1整合測試
UAThttps://uat-api.{domain}/api/v1使用者驗收
PRODhttps://api.{domain}/api/v1正式環境

10.2 變更紀錄

日期版本變更內容類型
{日期}{版本}{變更描述}Breaking / Non-Breaking

10.3 相關工具

工具用途連結
Swagger UIAPI 互動式文件{URL}
Postman CollectionAPI 測試集合{URL}

📖 使用說明

  • 環境 URL 需與 DevOps 團隊確認,確保 DNS 與 TLS 憑證就緒
  • 變更紀錄標記 Breaking / Non-Breaking 協助使用者評估升級影響
  • Postman Collection 可匯出分享給前端或第三方開發者

💡 範例

10.2 變更紀錄

日期版本變更內容類型
2026-05-18v1.0初版發布:Employees, Leaves, Payrolls API-
2026-06-01v1.1新增 delegateId 欄位於 LeaveRequestNon-Breaking
2026-07-15v1.2新增 /leaves/{id}/approve 端點Non-Breaking

11. 審查與驗證

本節供審查者使用,也用來檢查 AI 依本範本產出的文件是否正確;對應《軟體開發標準程序教學手冊》v2.0 各章的「審查與驗證」。

自動檢查

檢查項目方法
OpenAPI lintnpx @stoplight/spectral-cli lint openapi.yaml --fail-severity=warn(v2.0 範例已通過,含路徑版本號企業規則)
JSON 範例合法每個 json 區塊可被 JSON 解析器解析;含 HTTP 標頭的範例改用 http 區塊
錯誤格式整合測試斷言 Content-Type: application/problem+json 與 type、title、status

人工審查問題

  1. 端點、資料模型與 OpenAPI 檔三處的欄位與列舉值一致嗎?
  2. 清單 API 是否有分頁上限?非冪等 POST 是否需要冪等鍵?
  3. 不相容變更是否升主版號,並以 Deprecation/Sunset 標頭預告?
  4. 401/403/404 的語意是否正確(無權查看的資源可回 404)?

AI 常見錯誤

  • 錯誤回應仍用自訂格式,或把 422 寫成 Unprocessable Entity。
  • OpenAPI 範例引用未定義的 schema(v1.x 範本即有此問題,lint 會失敗)。
  • JSON 範例中夾帶 // 註解,導致不是合法 JSON。

📌 範本使用注意事項

  1. 本範本依據 OpenAPI Specification 3.1 標準編製
  2. 建議同時維護本文件(人類可讀)與 OpenAPI yaml 檔案(機器可讀)
  3. API 設計建議遵循:REST 最佳實踐、一致命名、最小暴露原則
  4. 所有 API 端點需通過 Security Review 後方可發布
  5. 建議搭配 Contract Testing 確保 API 實作與規格一致