Ahad Rafat Talebi
Ahad Rafat Talebi

Reputation: 321

How to set response class in FastAPI?

Using orjson to serializing response has a remarkable effect on the speed of fastAPI restful services, specifically for very big objects. As I have read in the official documentation, we can use the response class directly as a parameter of api method. The problem is that when I use the ORJSONResponse directly as a function it works; however, it doesn't work when passing it into parameter esponse_class=ORJSONResponse.

1. sample code with direct calling of ORJSONResponse():

this code run in 75ms ,size 6.6 MB that shows orjson serialization works properly. It's faster than .net core and it is what I need.

from fastapi import APIRouter

from fastapi.responses import ORJSONResponse

router=APIRouter()
__all__=["router"]

siz=1000000
ret=[None]*siz
for i in range(0,siz-1):
    ret[i]=i

@router.get("/planlist"))
def plan_list():
    ORJSONResponse(ret)
   

2. sample code with passing ORJSONResponse as parameter:

this code runs just like without response class set. it takes 876 ms more than 10 times longer in the same 6.6MB size. it shows orjson has not been set correctly.

from fastapi import APIRouter
from fastapi.responses import ORJSONResponse

router=APIRouter()
__all__=["router"]

siz=1000000
ret=[None]*siz
for i in range(0,siz-1):
    ret[i]=i

@router.get("/planlist",response_class=ORJSONResponse)
def plan_list():

    for i in range(0,siz-1):
        ret[i]=i

    return ret

Test platform

  • Test client: ansomnia core 2020.4.1, same results in postman 7.34.0
  • Os: MacOS catalina 10.15.7, same results for windows 10
  • cpu: core i9

Upvotes: 2

Views: 6851

Answers (2)

K14
K14

Reputation: 191

You can now use orjson as a default response class/type as mentioned in the docs

A small example

from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI(default_response_class=ORJSONResponse)


@app.get("/items/")
async def read_items():
    return [{"item_id": "Foo"}]

Upvotes: 1

Yagiz Degirmenci
Yagiz Degirmenci

Reputation: 20628

Also, we have documentation for Returning a Response Directly.

So you can use this, not a bad practice.

return ORJSONResponse(content=data)

But this will skip the validation, serialization and automatic documentation, which will give you huge flexibility and performance but which also means, you need to make sure the contents are ready for it and you need to manually design OpenAPI schemas.

Upvotes: 4

Related Questions