フォームとファイルをリクエストする¶
File と Form を同時に使用して、ファイルとフォームフィールドを定義できます。
情報
アップロードされたファイルやフォームデータを受信するには、まず python-multipart をインストールしてください。
仮想環境を作成し、アクティブ化してからインストールしてください。たとえば、
$ pip install python-multipart
File と Form をインポートする¶
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,
}
File と Form パラメータを定義する¶
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 として宣言できます。
Warning
1つの *パス操作* で複数の File と Form パラメータを宣言できますが、JSON として受け取ると予想される Body フィールドを同時に宣言することはできません。これは、リクエストのボディが application/json ではなく multipart/form-data を使用してエンコードされるためです。
これはFastAPIの制限ではなく、HTTPプロトコルの一部です。
まとめ¶
同じリクエストでデータとファイルを受け取る必要がある場合は、File と Form を一緒に使用します。