Caching helps your FastAPI app respond faster by saving data it already got. This means less waiting for users and less work for your server.
Caching strategies in FastAPI
from fastapi import FastAPI from fastapi_cache import FastAPICache from fastapi_cache.backends.inmemory import InMemoryBackend from fastapi_cache.decorator import cache app = FastAPI() @app.on_event("startup") async def startup(): FastAPICache.init(InMemoryBackend()) @app.get("/items/{item_id}") @cache(expire=60) async def read_item(item_id: int): # simulate slow operation return {"item_id": item_id, "value": "some data"}
The @cache decorator tells FastAPI to save the response for a set time (in seconds).
You must initialize the cache backend (like in-memory or Redis) when the app starts.
from fastapi_cache.decorator import cache @cache(expire=120) async def get_data(): return {"data": "cached for 2 minutes"}
@cache(expire=0) async def get_fresh_data(): return {"data": "no caching"}
import aioredis from fastapi_cache.backends.redis import RedisBackend @app.on_event("startup") async def startup(): redis = aioredis.from_url("redis://localhost") FastAPICache.init(RedisBackend(redis))
This FastAPI app has one endpoint that waits 2 seconds before returning data. But thanks to caching, if you call it again within 10 seconds, it returns instantly.
from fastapi import FastAPI from fastapi_cache import FastAPICache from fastapi_cache.backends.inmemory import InMemoryBackend from fastapi_cache.decorator import cache import asyncio app = FastAPI() @app.on_event("startup") async def startup(): FastAPICache.init(InMemoryBackend()) @app.get("/slow-data/{item_id}") @cache(expire=10) async def slow_data(item_id: int): await asyncio.sleep(2) # simulate slow operation return {"item_id": item_id, "info": "This data is cached for 10 seconds"}
In-memory cache is simple but resets when the app restarts.
For production, use Redis or another persistent cache backend.
Set cache expiration wisely to balance freshness and speed.
Caching saves repeated work and speeds up your FastAPI app.
Use the @cache decorator with an expiration time to enable caching.
Choose the right cache backend for your needs, like in-memory for testing or Redis for production.
Practice
Solution
Step 1: Understand caching concept
Caching stores results of expensive operations to reuse later.Step 2: Identify caching benefit in FastAPI
This reuse saves repeated work and speeds up response times.Final Answer:
To save repeated work and speed up response times -> Option DQuick Check:
Caching purpose = speed up responses [OK]
- Thinking caching increases code size
- Believing caching slows down the app
- Confusing caching with deleting data
Solution
Step 1: Recall FastAPI cache decorator syntax
The correct decorator is@cache(expire=seconds)to set expiration time.Step 2: Match options with correct syntax
Only@cache(expire=60)matches the correct pattern.Final Answer:
@cache(expire=60) -> Option AQuick Check:
Decorator with expire=60 is correct [OK]
- Using wrong decorator names like @cache_time
- Using incorrect parameter names like expiration
- Passing expiration time without parameter name
/data within 10 seconds?from fastapi import FastAPI
from fastapi_cache.decorator import cache
app = FastAPI()
@cache(expire=10)
async def get_data():
print('Fetching data')
return {'value': 42}
@app.get('/data')
async def data():
return await get_data()Solution
Step 1: Check for cache initialization
The code uses @cache but lacks FastAPICache.init with a backend on startup.Step 2: Analyze execution
Without init, FastAPICache.get raises AttributeError on first call, before executing get_data or printing.Final Answer:
Error because cache decorator is missing setup -> Option CQuick Check:
Missing FastAPICache.init causes runtime error [OK]
- Assuming caching works without FastAPICache.init, print once only
- Thinking no caching, print every call
- Believing cache expires immediately
from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend
app = FastAPI()
@app.on_event('startup')
async def startup():
FastAPICache.init(InMemoryBackend())
@cache(expire=30)
async def get_info():
return {'info': 'cached data'}Solution
Step 1: Check imports for cache decorator
The code uses@cachebut does not import it from fastapi_cache.decorator.Step 2: Verify other parts for correctness
FastAPICache.init is correctly called; InMemoryBackend needs no parameters; event name 'startup' is correct.Final Answer:
Cache decorator is used without importing it -> Option BQuick Check:
Missing import of cache decorator causes error [OK]
- Forgetting to import cache decorator
- Passing Redis URL to InMemoryBackend
- Renaming startup event incorrectly
get_user_profile function?from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
import aioredis
app = FastAPI()
@app.on_event('startup')
async def startup():
redis = aioredis.from_url('redis://localhost')
FastAPICache.init(RedisBackend(redis), prefix='fastapi-cache')
@cache(expire=300)
async def get_user_profile(user_id: int):
# Simulate fetching user profile
return {'user_id': user_id, 'name': 'Alice'}Solution
Step 1: Verify Redis backend initialization
Using aioredis.from_url and passing RedisBackend(redis) is correct for Redis caching.Step 2: Check cache decorator usage
@cache(expire=300) sets 5 minutes expiration correctly in seconds.Final Answer:
Correct setup: Redis backend initialized with aioredis, cache decorator with expire=300 -> Option AQuick Check:
Redis backend + expire=300 seconds = correct caching [OK]
- Passing Redis URL string directly instead of aioredis instance
- Using expire in milliseconds instead of seconds
- Calling FastAPICache.init inside cached function
Ready to prove it?
Pass the test and this pattern moves unknown
