Skip to content

Request Forms and Files

You can define files and form fields at the same time using File and Form.

Import File and Form

from fastapi import FastAPI, File, Form

app = FastAPI()


@app.post("/files/")
async def create_file(*, file: bytes = File(...), token: str = Form(...)):
    return {"file_size": len(file), "token": token}

Define File and Form parameters

Create file and form parameters the same way you would for Body or Query:

from fastapi import FastAPI, File, Form

app = FastAPI()


@app.post("/files/")
async def create_file(*, file: bytes = File(...), token: str = Form(...)):
    return {"file_size": len(file), "token": token}

The files and form fields will be uploaded as form data and you will receive the files and form fields.

Warning

You can declare multiple File and Form parameters in a path operation, but you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json.

This is not a limitation of FastAPI, it's part of the HTTP protocol.

Recap

Use File and Form together when you need to receive data and files in the same request.