コンテンツへスキップ

メタデータとドキュメントのURL

**FastAPI**アプリケーションでは、いくつかのメタデータ設定をカスタマイズできます。

APIのメタデータ

OpenAPI仕様と自動APIドキュメントUIで使用される以下のフィールドを設定できます。

パラメータ 説明
title str APIのタイトル。
summary str APIの短い要約。OpenAPI 3.1.0、FastAPI 0.99.0から利用可能。
description str APIの短い説明。Markdownを使用できます。
version string APIのバージョン。これは、OpenAPIではなく、独自のアプリケーションのバージョンです。例:2.5.0
terms_of_service str APIの利用規約へのURL。指定する場合は、URLでなければなりません。
contact dict 公開されているAPIの連絡先情報。いくつかのフィールドを含めることができます。
contactフィールド
パラメータ説明
namestr連絡担当者/組織の識別名。
urlstr連絡先情報へのURL。URL形式でなければなりません。
emailstr連絡担当者/組織のメールアドレス。メールアドレス形式でなければなりません。
license_info dict 公開されているAPIのライセンス情報。いくつかのフィールドを含めることができます。
license_infoフィールド
パラメータ説明
namestr必須license_infoが設定されている場合)。APIで使用されるライセンス名。
identifierstrAPIのSPDXライセンス式。identifierフィールドはurlフィールドと相互に排他的です。OpenAPI 3.1.0、FastAPI 0.99.0から利用可能。
urlstrAPIで使用されるライセンスへのURL。URL形式でなければなりません。

以下の様に設定できます。

from fastapi import FastAPI

description = """
ChimichangApp API helps you do awesome stuff. 🚀

## Items

You can **read items**.

## Users

You will be able to:

* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""

app = FastAPI(
    title="ChimichangApp",
    description=description,
    summary="Deadpool's favorite app. Nuff said.",
    version="0.0.1",
    terms_of_service="http://example.com/terms/",
    contact={
        "name": "Deadpoolio the Amazing",
        "url": "http://x-force.example.com/contact/",
        "email": "dp@x-force.example.com",
    },
    license_info={
        "name": "Apache 2.0",
        "url": "https://apache.dokyumento.jp/licenses/LICENSE-2.0.html",
    },
)


@app.get("/items/")
async def read_items():
    return [{"name": "Katana"}]

ヒント

descriptionフィールドにはMarkdownを書くことができ、出力時にレンダリングされます。

この設定により、自動APIドキュメントは以下のようになります。

ライセンス識別子

OpenAPI 3.1.0とFastAPI 0.99.0以降、urlの代わりにidentifierを使用してlicense_infoを設定することもできます。

例:

from fastapi import FastAPI

description = """
ChimichangApp API helps you do awesome stuff. 🚀

## Items

You can **read items**.

## Users

You will be able to:

* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""

app = FastAPI(
    title="ChimichangApp",
    description=description,
    summary="Deadpool's favorite app. Nuff said.",
    version="0.0.1",
    terms_of_service="http://example.com/terms/",
    contact={
        "name": "Deadpoolio the Amazing",
        "url": "http://x-force.example.com/contact/",
        "email": "dp@x-force.example.com",
    },
    license_info={
        "name": "Apache 2.0",
        "identifier": "MIT",
    },
)


@app.get("/items/")
async def read_items():
    return [{"name": "Katana"}]

タグのメタデータ

パラメータopenapi_tagsを使用して、パスオペレーションをグループ化するのに使用されるさまざまなタグに追加のメタデータを追加することもできます。

各タグに1つの辞書を含むリストを取ります。

各辞書は以下を含めることができます。

  • name必須):パスオペレーションAPIRoutertagsパラメータで使用されるものと同じタグ名を持つstr
  • description:タグの短い説明を含むstr。Markdownを含めることができ、ドキュメントUIに表示されます。
  • externalDocs:以下のものを持つ外部ドキュメントを記述するdict
    • description:外部ドキュメントの短い説明を含むstr
    • url必須):外部ドキュメントのURLを含むstr

タグのメタデータの作成

usersitemsのタグの例で試してみましょう。

タグのメタデータを作成し、openapi_tagsパラメータに渡します。

from fastapi import FastAPI

tags_metadata = [
    {
        "name": "users",
        "description": "Operations with users. The **login** logic is also here.",
    },
    {
        "name": "items",
        "description": "Manage items. So _fancy_ they have their own docs.",
        "externalDocs": {
            "description": "Items external docs",
            "url": "https://fastapi.dokyumento.jp/",
        },
    },
]

app = FastAPI(openapi_tags=tags_metadata)


@app.get("/users/", tags=["users"])
async def get_users():
    return [{"name": "Harry"}, {"name": "Ron"}]


@app.get("/items/", tags=["items"])
async def get_items():
    return [{"name": "wand"}, {"name": "flying broom"}]

説明の中にMarkdownを使用できることに注意してください。例えば"login"は太字(login)で、"fancy"は斜体(fancy)で表示されます。

ヒント

使用するすべてのタグにメタデータを追加する必要はありません。

タグの使用

パスオペレーション(およびAPIRouter)にtagsパラメータを使用して、異なるタグに割り当てます。

from fastapi import FastAPI

tags_metadata = [
    {
        "name": "users",
        "description": "Operations with users. The **login** logic is also here.",
    },
    {
        "name": "items",
        "description": "Manage items. So _fancy_ they have their own docs.",
        "externalDocs": {
            "description": "Items external docs",
            "url": "https://fastapi.dokyumento.jp/",
        },
    },
]

app = FastAPI(openapi_tags=tags_metadata)


@app.get("/users/", tags=["users"])
async def get_users():
    return [{"name": "Harry"}, {"name": "Ron"}]


@app.get("/items/", tags=["items"])
async def get_items():
    return [{"name": "wand"}, {"name": "flying broom"}]

情報

パスオペレーションの設定で、タグの詳細について説明しています。

ドキュメントの確認

ドキュメントを確認すると、追加のメタデータが表示されます。

タグの順序

各タグのメタデータディクショナリの順序は、ドキュメントUIに表示される順序も定義します。

例えば、アルファベット順ではusersitemsの後に来るはずですが、メタデータがリストの最初のディクショナリとして追加されているため、先に表示されます。

OpenAPI URL

デフォルトでは、OpenAPIスキーマは/openapi.jsonで提供されます。

しかし、openapi_urlパラメータで設定できます。

例えば、/api/v1/openapi.jsonで提供するように設定するには

from fastapi import FastAPI

app = FastAPI(openapi_url="/api/v1/openapi.json")


@app.get("/items/")
async def read_items():
    return [{"name": "Foo"}]

OpenAPIスキーマを完全に無効にするには、openapi_url=Noneに設定します。これにより、それを利用するドキュメントユーザーインターフェースも無効になります。

ドキュメントURL

含まれている2つのドキュメントユーザーインターフェースを設定できます。

  • Swagger UI/docsで提供されます。
    • docs_urlパラメータでURLを設定できます。
    • docs_url=Noneに設定して無効にすることができます。
  • ReDoc/redocで提供されます。
    • redoc_urlパラメータでURLを設定できます。
    • redoc_url=Noneに設定して無効にすることができます。

例えば、Swagger UIを/documentationで提供し、ReDocを無効にするには

from fastapi import FastAPI

app = FastAPI(docs_url="/documentation", redoc_url=None)


@app.get("/items/")
async def read_items():
    return [{"name": "Foo"}]