リクエストフォームとファイル¶
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
として宣言できます。
警告
パス操作で複数のFile
およびForm
パラメータを宣言できますが、リクエストのボディがapplication/json
の代わりにmultipart/form-data
を使用してエンコードされるため、JSONとして受信することを期待するBody
フィールドを宣言することもできません。
これはFastAPIの制限ではなく、HTTPプロトコルの一部です。
まとめ¶
同じリクエストでデータとファイルを受信する必要がある場合は、File
とForm
を一緒に使用してください。