0
0
Rest APIprogramming~30 mins

Cache invalidation strategies in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Cache Invalidation Strategies in REST API
📖 Scenario: You are building a simple REST API for a bookstore. To make the API faster, you want to add caching for book details. But when book information changes, the cache must be updated or cleared so users get fresh data.
🎯 Goal: Build a small REST API simulation that stores book data, caches book details, and uses a cache invalidation strategy to update the cache when book data changes.
📋 What You'll Learn
Create a dictionary called books with 3 books and their prices
Create a cache dictionary called cache to store cached book details
Write a function get_book_details(book_id) that returns cached data if available, otherwise fetches from books and caches it
Write a function update_book_price(book_id, new_price) that updates the book price and invalidates the cache for that book
Print the cached data before and after updating a book price to show cache invalidation
💡 Why This Matters
🌍 Real World
Caching is used in real REST APIs to speed up responses by storing data temporarily. Cache invalidation ensures users get fresh data when updates happen.
💼 Career
Understanding cache invalidation is important for backend developers working with APIs, improving performance and data accuracy.
Progress0 / 4 steps
1
Create the initial book data
Create a dictionary called books with these exact entries: 1: {'title': 'Python Basics', 'price': 29.99}, 2: {'title': 'REST APIs', 'price': 39.99}, 3: {'title': 'Data Science', 'price': 49.99}
Rest API
Need a hint?

Use a dictionary with keys 1, 2, 3 and values as dictionaries with keys 'title' and 'price'.

2
Create the cache dictionary
Create an empty dictionary called cache to store cached book details
Rest API
Need a hint?

Just create an empty dictionary named cache.

3
Write functions for caching and invalidation
Write a function called get_book_details(book_id) that returns cached data if book_id is in cache. Otherwise, fetch the book from books, store it in cache, and return it. Also write a function called update_book_price(book_id, new_price) that updates the price in books and removes the book_id from cache to invalidate it.
Rest API
Need a hint?

Use if book_id in cache to check cache. Use del cache[book_id] to invalidate cache.

4
Print cache before and after update
Print the result of get_book_details(2) to show cached data. Then call update_book_price(2, 44.99) to update the price and invalidate the cache. Finally, print get_book_details(2) again to show updated data is fetched and cached.
Rest API
Need a hint?

Print the result of get_book_details(2), then call update_book_price(2, 44.99), then print get_book_details(2) again.