Does FastAPI validate request Content-Type header and respond with 415 status when needed? #9371
Replies: 2 comments 1 reply
-
|
I am by no means an expert in how parsing requests works in FastAPI, but from what I can see in routing.py, Content-Type header is checked for the params.Body field. There are 2 logical branches:
All in all, this means that your body will be parsed no matter what you pass to the Body field's media_type argument. It is most likely used for generating OpenAPI schema and that's it. |
Beta Was this translation helpful? Give feedback.
-
I would say yes. I ran into the same problem today. Worked well in local with PostMan but got an internal error when using Here's how I've fixed it using FastAPI Dependencies and Header Parameters : from app.models import PydanticModel
from fastapi import APIRouter, Request, Response, HTTPException, Header, Depends
router = APIRouter()
def validate_content_type(content_type: str = Header(default=...)) -> None:
"""Refuse call that doesn't use the correct content-type"""
if content_type != "application/json":
raise HTTPException(
status_code=415,
detail="Unsupported Media Type. Content-Type must be 'application/json'",
)
@router.post(path="/random_request", dependencies=[Depends(dependency=validate_content_type)])
def random_request(
request: Request,
pydantic_model: PydanticModel,
) -> Response:
"""Random Request"""
# HTTP request without content-type application/json will be refused hereI'm using |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
Operating System
Windows
Operating System Details
No response
FastAPI Version
0.95.0
Python Version
3.10.4
Additional Context
I don't only expect FastAPI to return 415, I also expect it to be returned by raising an internal HTTPException so a custom exception handler can intercept it and return my own error response from it. Should I implement a custom FastAPI middleware to validate Content-Type matches the body param's media type?
Beta Was this translation helpful? Give feedback.
All reactions