a-luna / fastapi-redis-cache

A simple and robust caching solution for FastAPI that interprets request header values and creates proper response header values (powered by Redis)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can I cache POST requests?

kishvanchee opened this issue · comments

Hi, thank you for the library. Is there any way I can cache the POST requests as well? My use case is we do not change any resource per se in the server but we use POST to allow request body to have some parameters. There are high chances for repeated requests with the same combination. Can you please suggest how I can proceed with this using your library?

I also don't mind caching manually if the above solution is not possible. If manual caching is possible with your library, please let me know how I can do that.

I tried this out and it looks like even POST requests get cached as long as the return value of the API endpoint function is JSON serializable.

I ended up monkey patching this for the instance method and redefining what I wanted as

ALLOWED_HTTP_TYPES = ["GET"]
Allowed HTTP methods as GET and POST

commented

@kishvanchee Do you use this in production? As I want to do the same, my output data is JSON. However I do have an asynchronous dask client call in the view. But as the output is the same depending on input I think this should be ok right?

@mayurpande @kishvanchee Could you please share the response format snippet where it returns json in fastapi. The JSONResponse actually returns Object of type <class 'starlette.responses.JSONResponse'>

INFO:fastapi_redis_cache.client: 06/30/2023 04:53:06 AM | FAILED_TO_CACHE_KEY: Object of type <class 'starlette.responses.JSONResponse'> is not JSON-serializable: