The value of Content-Type is converted to binary issue with FastAPI(fastapi==0.111.1)

How to solve the response header’s content-type is change to binary prefix b’text/html; charset=utf-8’ issue ?

Content-Type: b’text/html; charset=utf-8’

Please check the following API
The API implement is as the following:

from fastapi.responses import HTMLResponse
from fastapi import APIRouter
service = os.getenv(“SERVICE”, default = “rechargecoins-api”)

@router.get(‘/home’, response_class=HTMLResponse)
async def home():
html_content = “ok1”
response = HTMLResponse(content=html_content, status_code=200)
return response

I run this API at local is working correctly.

However, deployment to vercel, the response’s header is incorrect

Hi, @millerlai!

It looks like the issue you’re facing with the Content-Type header showing up as b'text/html; charset=utf-8' is because of the response being interpreted as a byte string.

The b prefix indicates that the string is in bytes format rather than a regular string. This usually happens when there is a mismatch in the encoding or the way the headers are set in your FastAPI response.

To fix this issue, you need to ensure that the Content-Type header is explicitly set and correctly encoded.

Could you try changing:

response.headers['Content-Type'] = 'text/html; charset=utf-8

Also cross-posting this message from another thread that may be helpful.

Hi Pawlean! I’m encountering the same issue here and was not able to fix it. I’m a bit puzzled because it works fine on my local machine and only has this issue on Vercel. I added some middleware, but no dice.

Example header…
content-type: b’application/json; charset=utf-8’

Would this imply it’s an encoding or decoding issue? My site is https://howdy.new if you’d like to see this in action.

# Middleware to ensure all headers are strings
@app.middleware(“http”)
async def ensure_string_headers_middleware(request: Request, call_next):
response = await call_next(request)

if isinstance(response, StreamingResponse):
    # For streaming responses, we need to modify the headers in a different way
    original_headers = response.headers
    response.raw_headers = [(k.encode('utf-8'), v.encode('utf-8')) 
                            for k, v in ensure_string_headers(original_headers).items()]
elif isinstance(response, Response):
    # For regular responses, we can modify the headers directly
    response.headers = ensure_string_headers(response.headers)

return response

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.