0
0
FastAPIframework~30 mins

Caching strategies in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Caching Strategies with FastAPI
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use app = FastAPI() to create the app. Use @app.get("/user/{user_id}") to define the route.