コンテンツへスキップ

OpenAPIでの追加レスポンス

Warning

これはかなり高度なトピックです。

FastAPI を始めたばかりであれば、これは必要ないかもしれません。

追加のステータスコード、メディアタイプ、説明などを指定して、追加のレスポンスを宣言できます。

これらの追加レスポンスはOpenAPIスキーマに含まれるため、APIドキュメントにも表示されます。

ただし、これらの追加レスポンスには、ステータスコードとコンテンツを含む `JSONResponse` のような `Response` を直接返すことを確認する必要があります。

model を使用した追加レスポンス

パス操作デコレータresponses パラメータを渡すことができます。

これは dict を受け取ります。キーは各レスポンスのステータスコード (200 など) であり、値はそれぞれの情報を含む別の dict です。

これらのレスポンス dict のそれぞれは、response_model と同様に、Pydantic モデルを含む model キーを持つことができます。

FastAPI はそのモデルを受け取り、JSONスキーマを生成し、OpenAPIの適切な場所に含めます。

たとえば、ステータスコード 404 と Pydantic モデル Message を持つ別のレスポンスを宣言するには、次のように記述できます。

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    value: str


class Message(BaseModel):
    message: str


app = FastAPI()


@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read_item(item_id: str):
    if item_id == "foo":
        return {"id": "foo", "value": "there goes my hero"}
    return JSONResponse(status_code=404, content={"message": "Item not found"})

Note

JSONResponse を直接返さなければならないことに注意してください。

情報

model キーはOpenAPIの一部ではありません。

FastAPI はそこからPydanticモデルを取得し、JSONスキーマを生成して、適切な場所に配置します。

適切な場所は次のとおりです。

  • キー content には、次の情報を含む別のJSONオブジェクト (dict) が値として設定されます。
    • メディアタイプのキー (例: application/json)。これには、さらに別のJSONオブジェクトが値として含まれ、それにさらに含まれるのは、
      • キー schema で、値としてモデルのJSONスキーマが設定されます。ここが正しい場所です。
        • FastAPI は、OpenAPIの別の場所にあるグローバルJSONスキーマへの参照をここに追加します。これにより、他のアプリケーションやクライアントはこれらのJSONスキーマを直接使用でき、より良いコード生成ツールを提供できます。

このパス操作に対してOpenAPIで生成されるレスポンスは次のようになります。

{
    "responses": {
        "404": {
            "description": "Additional Response",
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/Message"
                    }
                }
            }
        },
        "200": {
            "description": "Successful Response",
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/Item"
                    }
                }
            }
        },
        "422": {
            "description": "Validation Error",
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/HTTPValidationError"
                    }
                }
            }
        }
    }
}

スキーマはOpenAPIスキーマ内の別の場所を参照しています。

{
    "components": {
        "schemas": {
            "Message": {
                "title": "Message",
                "required": [
                    "message"
                ],
                "type": "object",
                "properties": {
                    "message": {
                        "title": "Message",
                        "type": "string"
                    }
                }
            },
            "Item": {
                "title": "Item",
                "required": [
                    "id",
                    "value"
                ],
                "type": "object",
                "properties": {
                    "id": {
                        "title": "Id",
                        "type": "string"
                    },
                    "value": {
                        "title": "Value",
                        "type": "string"
                    }
                }
            },
            "ValidationError": {
                "title": "ValidationError",
                "required": [
                    "loc",
                    "msg",
                    "type"
                ],
                "type": "object",
                "properties": {
                    "loc": {
                        "title": "Location",
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    },
                    "msg": {
                        "title": "Message",
                        "type": "string"
                    },
                    "type": {
                        "title": "Error Type",
                        "type": "string"
                    }
                }
            },
            "HTTPValidationError": {
                "title": "HTTPValidationError",
                "type": "object",
                "properties": {
                    "detail": {
                        "title": "Detail",
                        "type": "array",
                        "items": {
                            "$ref": "#/components/schemas/ValidationError"
                        }
                    }
                }
            }
        }
    }
}

メインレスポンスの追加メディアタイプ

同じ responses パラメータを使用して、同じメインレスポンスに異なるメディアタイプを追加できます。

たとえば、パス操作がJSONオブジェクト (メディアタイプ application/json) またはPNG画像を返すことができることを宣言して、追加のメディアタイプ image/png を追加できます。

from typing import Union

from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    value: str


app = FastAPI()


@app.get(
    "/items/{item_id}",
    response_model=Item,
    responses={
        200: {
            "content": {"image/png": {}},
            "description": "Return the JSON item or an image.",
        }
    },
)
async def read_item(item_id: str, img: Union[bool, None] = None):
    if img:
        return FileResponse("image.png", media_type="image/png")
    else:
        return {"id": "foo", "value": "there goes my hero"}

Note

FileResponse を使用して画像を直接返す必要があることに注意してください。

情報

responses パラメータで異なるメディアタイプを明示的に指定しない限り、FastAPIはレスポンスがメインレスポンスクラスと同じメディアタイプ (デフォルト application/json) であると想定します。

ただし、メディアタイプが None のカスタムレスポンスクラスを指定した場合、FastAPIは関連するモデルを持つ追加レスポンスに対して application/json を使用します。

情報の結合

response_modelstatus_coderesponses パラメータなど、複数の場所からレスポンス情報を結合することもできます。

デフォルトのステータスコード 200 (または必要に応じてカスタム) を使用して response_model を宣言し、その後、responses でその同じレスポンスの追加情報をOpenAPIスキーマに直接宣言できます。

FastAPIresponses からの追加情報を保持し、モデルのJSONスキーマと結合します。

たとえば、Pydanticモデルを使用し、カスタム description を持つステータスコード 404 のレスポンスを宣言できます。

そして、response_model を使用し、カスタム example を含むステータスコード 200 のレスポンスも宣言できます。

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    value: str


class Message(BaseModel):
    message: str


app = FastAPI()


@app.get(
    "/items/{item_id}",
    response_model=Item,
    responses={
        404: {"model": Message, "description": "The item was not found"},
        200: {
            "description": "Item requested by ID",
            "content": {
                "application/json": {
                    "example": {"id": "bar", "value": "The bar tenders"}
                }
            },
        },
    },
)
async def read_item(item_id: str):
    if item_id == "foo":
        return {"id": "foo", "value": "there goes my hero"}
    else:
        return JSONResponse(status_code=404, content={"message": "Item not found"})

これらはすべて結合され、OpenAPIに含められ、APIドキュメントに表示されます。

事前定義されたレスポンスとカスタムレスポンスの結合

多くのパス操作に適用される事前定義されたレスポンスを持たせたいが、各パス操作に必要なカスタムレスポンスとそれらを結合したい場合があります。

そのような場合、Pythonの「辞書のアンパック」技術を **dict_to_unpack で使用できます。

old_dict = {
    "old key": "old value",
    "second old key": "second old value",
}
new_dict = {**old_dict, "new key": "new value"}

ここで、new_dict には old_dict のすべてのキーと値のペアに加えて、新しいキーと値のペアが含まれます。

{
    "old key": "old value",
    "second old key": "second old value",
    "new key": "new value",
}

この技術を使用して、パス操作で事前定義されたレスポンスを再利用し、追加のカスタムレスポンスと結合できます。

例えば

from typing import Union

from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    value: str


responses = {
    404: {"description": "Item not found"},
    302: {"description": "The item was moved"},
    403: {"description": "Not enough privileges"},
}


app = FastAPI()


@app.get(
    "/items/{item_id}",
    response_model=Item,
    responses={**responses, 200: {"content": {"image/png": {}}}},
)
async def read_item(item_id: str, img: Union[bool, None] = None):
    if img:
        return FileResponse("image.png", media_type="image/png")
    else:
        return {"id": "foo", "value": "there goes my hero"}

OpenAPIレスポンスに関する詳細情報

レスポンスに含めることができる内容の詳細は、OpenAPI仕様の次のセクションで確認できます。

  • OpenAPI Responses Object。これには Response Object が含まれます。
  • OpenAPI Response Objectdescriptionheaderscontent (この中に異なるメディアタイプとJSONスキーマを宣言します)、および links など、これをそのまま responses パラメータ内の各レスポンスに含めることができます。