コンテンツにスキップ

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

🌐 Translation by AI and humans

This translation was made by AI guided by humans. 🤝

It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖

You can improve this translation by helping us guide the AI LLM better.

English version

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を一緒に使用します。