Search code examples
pythonhttp-headersfastapiorjson

Why Http headers is being vanished when using ORJSONResponse() in fastAPI?


Http headers can be modified in fastAPI; however when I tried to use faster serializer (in this instance ORJSONResponse) in order to have faster response, all added or modified headers confusingly is being vanished. I don't have any idea that why it happens and how can I fix it? also we got the same result for UJSONResponse too.

thanks for sharing your experiences.

A. This code can't modify headers

from fastapi import APIRouter, Response
from fastapi.responses import ORJSONResponse
router = APIRouter()

@router.get("/test")
async def plan_list(response:Response):
    response.headers["test-header"]="test-value"
    return ORJSONResponse(list(range(10000)))

Output header list of code A:

date: Thu, 22 Oct 2020 18:42:19 GMT
server: uvicorn
content-length: 48891
content-type: application/json

B. This code modifies headers normally

from fastapi import APIRouter, Response
from fastapi.responses import ORJSONResponse
router = APIRouter()

@router.get("/test")
async def plan_list(response:Response):
    response.headers["test-header"]="test-value"
    return list(range(10000))

Output header list of code B:

date: Thu, 22 Oct 2020 18:42:19 GMT
server: uvicorn
content-length: 48891
content-type: application/json
test-header: test-value

test platform:

  • OS: macOS 10.15.7
  • client: insomnia 2020.14.1
  • python: 3.8.5

Solution

  • It was solved here thanks to amin jamal.

    
    from fastapi import APIRouter, Response, FastAPI
    from fastapi.responses import ORJSONResponse
    
    app = FastAPI()
    router = APIRouter()
    
    
    @router.get("/test")
    async def plan_list(response:Response):
           response.headers["test"]="test-value"
           return ORJSONResponse(list(range(10000)),headers=response.headers)
    
    
    
    app.include_router(router)