📖 Scenario: You are building a simple FastAPI web service that returns user profile data. To improve performance, you want to add caching so repeated requests for the same user ID return cached data instead of recomputing it.
🎯 Goal: Build a FastAPI app that caches user profile data in memory using a dictionary. The app should return cached data if available, otherwise generate and store it.
📋 What You'll Learn
Create a dictionary called cache to store cached user profiles.
Create a variable called cache_expiry_seconds set to 60 to define cache duration.
Write a function get_user_profile that checks the cache and returns cached data if valid, or generates new data and caches it.
Add a FastAPI route /user/{user_id} that calls get_user_profile and returns the profile.
💡 Why This Matters
🌍 Real World
Caching is used in web services to reduce repeated work and speed up responses, improving user experience and reducing server load.
💼 Career
Understanding caching strategies is important for backend developers to optimize API performance and scalability.
Progress0 / 4 steps
1
Create the cache dictionary
Create a dictionary called cache that will store cached user profiles with their timestamps.
FastAPI
Hint
Use cache = {} to create an empty dictionary.
2
Add cache expiry configuration
Create a variable called cache_expiry_seconds and set it to 60 to define how long cached data is valid in seconds.
FastAPI
Hint
Use cache_expiry_seconds = 60 to set the cache duration.
3
Write the caching logic function
Write a function called get_user_profile that takes user_id as input. It should check if user_id is in cache and if the cached data is not expired. If valid, return cached data. Otherwise, generate new profile data as a dictionary with user_id and name as 'User {user_id}', store it in cache with the current timestamp, and return it. Use time.time() for timestamps.
FastAPI
Hint
Check if user_id is in cache. If yes, check timestamp. If expired or missing, create new profile and store with timestamp.
4
Add FastAPI route to serve cached profiles
Import FastAPI and create an app instance called app. Add a route /user/{user_id} using @app.get that calls get_user_profile with user_id and returns the result.
FastAPI
Hint
Use app = FastAPI() to create the app. Use @app.get("/user/{user_id}") to define the route.
Practice
(1/5)
1. What is the main purpose of using caching in a FastAPI application?
easy
A. To increase the size of the application code
B. To remove all data from the server
C. To make the app slower for testing
D. To save repeated work and speed up response times
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 D
Quick Check:
Caching purpose = speed up responses [OK]
Hint: Caching means saving work to respond faster [OK]
Common Mistakes:
Thinking caching increases code size
Believing caching slows down the app
Confusing caching with deleting data
2. Which of the following is the correct way to apply caching with expiration in FastAPI using the decorator?
easy
A. @cache(expire=60)
B. @cache_time(60)
C. @cache(expiration=60)
D. @cache(60_seconds)
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 A
Quick Check:
Decorator with expire=60 is correct [OK]
Hint: Use @cache with expire=seconds for expiration [OK]
Common Mistakes:
Using wrong decorator names like @cache_time
Using incorrect parameter names like expiration
Passing expiration time without parameter name
3. Given this FastAPI code snippet, what will be the output on the second call to /data within 10 seconds?
Hint: Cache decorator requires FastAPICache.init on startup [OK]
Common Mistakes:
Assuming caching works without FastAPICache.init, print once only
Thinking no caching, print every call
Believing cache expires immediately
4. Identify the error in this FastAPI caching setup:
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'}
medium
A. InMemoryBackend requires a Redis URL parameter
B. Cache decorator is used without importing it
C. Missing await keyword when calling FastAPICache.init
D. Startup event should be named 'start' instead of 'startup'
Solution
Step 1: Check imports for cache decorator
The code uses @cache but 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 B
Quick Check:
Missing import of cache decorator causes error [OK]
Hint: Always import @cache decorator before using it [OK]
Common Mistakes:
Forgetting to import cache decorator
Passing Redis URL to InMemoryBackend
Renaming startup event incorrectly
5. You want to cache user profile data in FastAPI using Redis backend with a 5-minute expiration. Which setup correctly initializes caching and applies it to the 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'}
hard
A. Correct setup: Redis backend initialized with aioredis, cache decorator with expire=300
B. Incorrect: RedisBackend needs a string URL, not aioredis instance
C. Incorrect: Cache decorator expire should be in milliseconds, not seconds
D. Incorrect: FastAPICache.init must be called inside the cached function
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 A