python data_error ai_generated true

RuntimeError: Request body exceeded maximum size (1000000 bytes)

ID: python/fastapi-request-body-too-large

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-07-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

The incoming request body is larger than the maximum allowed size set by the application.

generic

中文

传入的请求体大于应用设置的最大允许大小。

Workarounds

  1. 90% success Increase the maximum request body size
    from starlette.middleware.base import BaseHTTPMiddleware
    class LimitUploadSize(BaseHTTPMiddleware):
        async def dispatch(self, request, call_next):
            if request.headers.get('content-length'):
                if int(request.headers['content-length']) > 10 * 1024 * 1024:
                    raise HTTPException(status_code=413, detail="Request too large")
            return await call_next(request)
    app.add_middleware(LimitUploadSize)
  2. 80% success Use streaming to handle large bodies
    async def upload():
        async for chunk in request.stream():
            process_chunk(chunk)

Dead Ends

Common approaches that don't work:

  1. Truncating the request body on the client side 60% fail

    May lose data; not a server-side fix.

  2. Ignoring the error and retrying 95% fail

    Same error will occur until limit is increased or body is reduced.