Skip to content
ADP
API Design PrincipleBETA

[ADP-404] 驗證錯誤設計

對於問題類型為 validation-error 的情況,服務器預期會返回多個關於失敗部分的錯誤實例。

  • 所有驗證錯誤的驗證規則與格式,必須對應 OpenAPI 規範的 format 欄位(例如 email、uuid、date-time 等),以確保驗證一致性與可預測性。
  • 必須為驗證錯誤提供錯誤對象資訊陣列(在 errors 中,因為預期會有多個)

單個驗證錯誤對象的格式

json
[
    {
      "in": "[path|query|header|body]",
      "path": "#/json/pointer/to/failed/field",
      "invalidValue": "Optional invalid client input as a string.",
      "details": [
        {
          "key": "machine.readable.key1",
          "message": "First human-readable error message."
        },
        {
          "key": "machine.readable.key2",
          "message": "Another human-readable error message."
        }
      ]
    }
  ]

OpenAPI 3.1 範例

yaml
components:
  schemas:
    ValidationError:
      type: object
      required:
        - in
        - path
        - detail
      properties:
        in:
          type: string
          enum: [path, query, header, body]
        path:
          type: string
        detail:
          type: string
        invalidValue:
          type: string
        details:
          type: array
          items:
            type: object
            required:
              - key
              - message
            properties:
              key:
                type: string
              message:
                type: string
    
    ValidationErrorResponse:
      type: object
      required:
        - type
        - title
        - status
        - errors
      properties:
        type:
          type: string
          const: 'validation-error'
        title:
          type: string
        status:
          type: integer
          enum: [400]
        errors:
          type: array
          items:
            $ref: '#/components/schemas/ValidationError'

paths:
  /example:
    post:
      responses:
        '400':
          description: Bad Request
          content:
            application/problem+json:    
              schema:
                $ref: '#/components/schemas/ValidationErrorResponse'