[ADP-126] Content-Type
概述
在 RESTful API 設計中,Content-Type
標頭指定了發送到伺服器或由伺服器返回的資源的媒體類型。它確保伺服器和客戶端正確解釋訊息的內容。這個標頭對於請求和回應訊息都是必要的。
指導原則
- 當客戶端向伺服器發送數據時(例如通過 POST 或 PUT),它必須(MUST)包含
Content-Type
標頭以指明所發送數據的類型。- 常見的內容類型包括
application/json
,application/xml
,text/plain
等。
- 常見的內容類型包括
- 伺服器應該(MUST)在回應中包含
Content-Type
標頭以指定返回數據的類型。- 這有助於客戶端正確處理回應數據。
- 客戶端可以(MAY)使用
Accept
標頭來告知伺服器它可以處理的回應類型。請參閱 ADP-122: Accept。伺服器應該(SHOULD)尊重
Accept
標頭並返回可接受格式之一的數據,或者如果無法生成任何可接受的格式,則回應406 Not Acceptable
狀態碼。httpHTTP/1.1 406 Not Acceptable Content-Type: application/problem+json Content-Language: en { "type": "https://example.com/problems/not-acceptable", "title": "Not Acceptable", "status": 406, "detail": "The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.", "instance": "/users" }
示例
請求示例
客戶端發送 JSON 負載以創建新用戶:
http
POST /users
Content-Type: application/json
{
"name": "John Doe",
"email": "john.doe@example.com"
}
回應示例
伺服器回應 JSON 數據:
http
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 123,
"name": "John Doe",
"email": "john.doe@example.com"
}
OpenAPI 示例
以下是一個定義了適當 Content-Type
標頭的 OpenAPI 3.0 示例:
yaml
openapi: 3.1.0
info:
title: User API
version: 1.0.0
paths:
/users:
post:
summary: Create a new user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
email:
type: string
responses:
'200':
description: User created successfully
content:
application/json:
schema:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
'400':
description: Invalid input
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'406':
description: Not Acceptable
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
components:
schemas:
Error:
type: object
properties:
code:
type: integer
message:
type: string
Problem:
type: object
properties:
type:
type: string
format: uri
title:
type: string
status:
type: integer
detail:
type: string
instance:
type: string
format: uri
required:
- type
- title
- status
- detail
- instance
example:
type: "https://example.com/problems/not-acceptable"
title: "Not Acceptable"
status: 406
detail: "The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request."
instance: "/users"