Ir para o conteúdo

Formulários e Arquivos da Requisição

Você pode definir arquivos e campos de formulário ao mesmo tempo usando File e Form.

Informação

Para receber arquivos carregados e/ou dados de formulário, primeiro instale python-multipart.

Certifique-se de criar um ambiente virtual, ativá-lo e então instalar, por exemplo:

$ pip install python-multipart

Importe File e 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,
    }
🤓 Other versions and variants
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,
    }

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

Defina parâmetros de File e Form

Crie parâmetros de arquivo e formulário da mesma forma que você faria para Body ou 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,
    }
🤓 Other versions and variants
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,
    }

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

Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário.

E você pode declarar alguns dos arquivos como bytes e alguns como UploadFile.

Atenção

Você pode declarar vários parâmetros File e Form em uma operação de caminho, mas não é possível declarar campos Body para receber como JSON, pois a requisição terá o corpo codificado usando multipart/form-data ao invés de application/json.

Isso não é uma limitação do FastAPI, é parte do protocolo HTTP.

Recapitulando

Usar File e Form juntos quando precisar receber dados e arquivos na mesma requisição.