コンテンツへスキップ

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

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,
    }
from fastapi import FastAPI, File, Form, UploadFile
from typing_extensions import Annotated

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,
    }

ヒント

可能であれば、Annotatedバージョンを使用することを推奨します。

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のパラメータを定義

BodyまたはQueryの場合と同様に、ファイルおよびフォームのパラメータを作成します。

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,
    }
from fastapi import FastAPI, File, Form, UploadFile
from typing_extensions import Annotated

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,
    }

ヒント

可能であれば、Annotatedバージョンを使用することを推奨します。

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として宣言できます。

警告

パス操作で複数のFileおよびFormパラメータを宣言できますが、リクエストのボディがapplication/jsonの代わりにmultipart/form-dataを使用してエンコードされるため、JSONとして受信することを期待するBodyフィールドを宣言することもできません。

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

まとめ

同じリクエストでデータとファイルを受信する必要がある場合は、FileFormを一緒に使用してください。