Skip to content

Conversation

@YuriiMotov
Copy link
Member

@YuriiMotov YuriiMotov commented Dec 3, 2025

FastAPI currently allows configuring upload limits only at the application level (using middleware), which makes it difficult to apply different constraints to different endpoints.
In some cases you may want to specify different values for specific router or endpoint. Currently there is no such option.

The idea of this PR is to allow specifying such limits for routers and endpoints.

As an experiment, I implemented this for post method. If it's Ok then will implement for app, router and other methods

upload_file_router = APIRouter(form_max_files=100, max_part_size=1024*1024)


@upload_file_router.post(
    "/upload-multi", max_part_size=1024*1024*100,
    form_max_files=1000,
)
async def upload(files: List[UploadFile] = File(...)):
    pass


app = FastAPI(form_max_files=0, max_part_size=1024)

app.include_router(upload_file_router)

Related discussions:

@YuriiMotov YuriiMotov added the feature New feature or request label Dec 3, 2025
@YuriiMotov YuriiMotov force-pushed the allow-specifying-max-values-for-form branch from 6963426 to 45b472b Compare December 3, 2025 21:59
@YuriiMotov YuriiMotov changed the title ✨ Allow specifying max_field, max_files and max_part_size for path operations ✨ Allow specifying max_field, max_files and max_part_size for routers and path operations Dec 4, 2025
@dolfinus
Copy link
Contributor

dolfinus commented Dec 6, 2025

Instead of modifying app.post() method, maybe it should be a part of annotation?

@app.post("/data")
async def handle_fiels(
  files: Annotated[List[UploadFile], Field(max_items=10), File(max_size="10MiB")]
): ...

@YuriiMotov
Copy link
Member Author

Instead of modifying app.post() method, maybe it should be a part of annotation?

I think this is a bit different.. In my implementation max_field, max_files and max_part_size are used while parsing multipart data by Starlette. The idea of these parameters is to prevent the attacks when heavy requests are sent to cause "Out of memory" on server.
For now these parameters have defaults, but it's not easy to change these defaults for FastAPI app - people need to use middleware to call request.form() with custom parameters before validation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants