0
0
Rest APIprogramming~30 mins

Expiration-based caching in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Expiration-based caching in a REST API
📖 Scenario: You are building a simple REST API that returns data about products. To make your API faster and reduce repeated work, you want to add a cache that stores results temporarily. The cache should keep data only for a short time, then remove it automatically.
🎯 Goal: Build a basic expiration-based cache for your REST API. You will create a cache dictionary, set an expiration time, store data with timestamps, and return cached data only if it is still fresh.
📋 What You'll Learn
Create a cache dictionary to store product data and timestamps
Add a variable for cache expiration time in seconds
Write logic to check if cached data is still valid before returning it
Print the cached data or a message if cache expired
💡 Why This Matters
🌍 Real World
APIs often use caching to speed up responses and reduce repeated work. Expiration-based caching helps keep data fresh while saving resources.
💼 Career
Understanding caching is important for backend developers and API designers to build efficient and scalable web services.
Progress0 / 4 steps
1
Create the cache dictionary
Create a dictionary called cache that will store cached product data and their timestamps. Initialize it as an empty dictionary.
Rest API
Need a hint?

Use {} to create an empty dictionary in Python.

2
Set the cache expiration time
Create a variable called cache_expiration and set it to 10. This number means the cache will keep data for 10 seconds before it expires.
Rest API
Need a hint?

Just assign the number 10 to the variable cache_expiration.

3
Add caching logic with expiration check
Write code to store product data in cache with the current time, and check if cached data is still valid before returning it. Use variables product_id set to 101 and product_data set to {'name': 'Book', 'price': 12.99}. Use time.time() to get the current time. If cached data exists and is not expired, use it. Otherwise, update the cache with new data and timestamp.
Rest API
Need a hint?

Use time.time() to get current time and store it with the data in the cache dictionary.

4
Print the cached result
Write a print statement to display the cached_result variable.
Rest API
Need a hint?

Use print(cached_result) to show the cached data.