OpenAPI: 標準エラーレスポンス定義
OpenAPI 3.0で再利用可能なエラーレスポンススキーマを定義。RFC 7807 Problem Details、フィールドレベル詳細付きバリデーションエラー、一貫したエラーコードを解説。
Error Handling
詳細な説明
OpenAPIでの標準エラーレスポンス定義
一貫したエラーレスポンスはAPIの使いやすさに不可欠です。RFC 7807「HTTP APIのProblem Details」フォーマットが業界標準です。
エラースキーマ(RFC 7807)
components:
schemas:
Error:
type: object
required:
- type
- title
- status
properties:
type:
type: string
description: URI reference identifying the error type
title:
type: string
description: Short, human-readable summary
status:
type: integer
description: HTTP status code
detail:
type: string
description: Human-readable explanation
instance:
type: string
description: URI reference for this specific occurrence
ValidationError:
type: object
required:
- type
- title
- status
- errors
properties:
type:
type: string
title:
type: string
status:
type: integer
errors:
type: array
items:
type: object
properties:
field:
type: string
description: The field that failed validation
message:
type: string
description: What went wrong
code:
type: string
description: Machine-readable error code
再利用可能なレスポンスコンポーネント
components:
responses:
BadRequest:
description: Validation error
content:
application/json:
schema:
$ref: '#/components/schemas/ValidationError'
NotFound:
description: Resource not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Unauthorized:
description: Authentication required
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
再利用可能なレスポンスの使用
パス操作で参照します:
responses:
'400':
$ref: '#/components/responses/BadRequest'
'401':
$ref: '#/components/responses/Unauthorized'
'404':
$ref: '#/components/responses/NotFound'
APIの一般的なHTTPステータスコード
| コード | 意味 | 使用タイミング |
|---|---|---|
| 400 | Bad Request | バリデーションエラー、不正なJSON |
| 401 | Unauthorized | 認証が欠落または無効 |
| 403 | Forbidden | 認証済みだが権限不足 |
| 404 | Not Found | リソースが存在しない |
| 409 | Conflict | 重複リソースまたは状態の競合 |
| 422 | Unprocessable Entity | 意味的に無効なリクエスト |
| 429 | Too Many Requests | レート制限超過 |
| 500 | Internal Server Error | 予期しないサーバー障害 |
ユースケース
API全体で一貫したエラーハンドリング契約を確立するために使用。チームはこれを基盤として、すべてのエンドポイントが同じ形式でエラーを返すようにし、API利用者の開発者体験を向上させます。