Decoding non-utf-8 request bodies with fastapi

368 Views Asked by At

I have what feels like a simple question: I have a service using fastapi that receives requests in which the request bodies have been encoded using the ISO-8859-1 encoding and the content-type in the request header is set to text/plain;charset=ISO-8859-1.

I can manually decode the request body without issue:

async def myendpoint(request: Request) -> str:
    body = await request.body()
    content_type = request.headers.get("content-type", "")
    _, options = cgi.parse_header(content_type)
    encoding = options.get("charset", "utf-8")
    decoded_body = body.decode(encoding)
    return decoded_body

But I'd really like to have the endpoint take a pydantic model instead of a Request, in which case fastapi also decodes the request body automatically...and as far as I can tell, it always uses utf-8 regardless of what the content-type header says, and I can't find any way to alter this behavior.

Is there something really obvious that I'm missing here? I find it hard to believe that a service framework that automatically decodes the request body would just assume utf-8 for everything. And if this really is just how it works, do I have better options beyond doing the decoding (and validation through pydantic, and exception handling for that validation...) myself, in the endpoint function?

0

There are 0 best solutions below