コンテンツへスキップ

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

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

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,
    }
🤓 その他のバージョンとバリアント
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 パラメータを宣言できますが、JSON として受信することを期待する Body フィールドを宣言することはできません。これは、リクエストボディが application/json の代わりに multipart/form-data を使用してエンコードされるためです。

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

まとめ

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