コンテンツにスキップ

リクエストフォームとファイル

🌐 AI と人間による翻訳

この翻訳は、人間のガイドに基づいて AI によって作成されました。🤝

原文の意図を取り違えていたり、不自然な表現になっている可能性があります。🤖

AI LLM をより適切に誘導するのを手伝う ことで、この翻訳を改善できます。

英語版

FileFormを同時に使うことでファイルとフォームフィールドを定義することができます。

情報

アップロードされたファイルやフォームデータを受信するには、まずpython-multipartをインストールします。

仮想環境を作成し、それを有効化してから、例えば次のようにインストールしてください:

$ pip install python-multipart

FileFormのインポート

from typing import Annotated

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(
    file: Annotated[bytes, File()],
    fileb: Annotated[UploadFile, File()],
    token: Annotated[str, Form()],
):
    return {
        "file_size": len(file),
        "token": token,
        "fileb_content_type": fileb.content_type,
    }
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(
    file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
):
    return {
        "file_size": len(file),
        "token": token,
        "fileb_content_type": fileb.content_type,
    }

FileFormのパラメータの定義

ファイルやフォームのパラメータはBodyQueryの場合と同じように作成します:

from typing import Annotated

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(
    file: Annotated[bytes, File()],
    fileb: Annotated[UploadFile, File()],
    token: Annotated[str, Form()],
):
    return {
        "file_size": len(file),
        "token": token,
        "fileb_content_type": fileb.content_type,
    }
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(
    file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
):
    return {
        "file_size": len(file),
        "token": token,
        "fileb_content_type": fileb.content_type,
    }

ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。

また、いくつかのファイルをbytesとして、いくつかのファイルをUploadFileとして宣言することができます。

注意

path operationで複数のFileFormパラメータを宣言することができますが、JSONとして受け取ることを期待しているBodyフィールドを宣言することはできません。なぜなら、リクエストのボディはapplication/jsonの代わりにmultipart/form-dataを使ってエンコードされているからです。

これは FastAPI の制限ではなく、HTTPプロトコルの一部です。

まとめ

同じリクエストでデータやファイルを受け取る必要がある場合は、FileFormを一緒に使用します。