📖 Scenario: You are building a simple REST API that returns user profile data. To improve performance, you want to add validation-based caching. This means the API will store the last returned data and a validation token (like an ETag). When the client sends a request with the token, the API checks if the data has changed. If not, it returns a 304 Not Modified status instead of the full data.
🎯 Goal: Build a REST API endpoint that returns user data with validation-based caching using ETag headers.
📋 What You'll Learn
Create a dictionary called user_profile with exact keys and values
Create a variable called etag with the exact string value
Write a function called get_user_profile that takes a parameter client_etag and returns a tuple of (status_code, data_or_message)
Print the result of calling get_user_profile with client_etag set to the exact string "abc123"
💡 Why This Matters
🌍 Real World
Validation-based caching is used in web APIs to reduce data transfer and improve speed by sending data only when it changes.
💼 Career
Understanding caching and validation tokens like ETag is important for backend developers working on efficient REST APIs.
Progress0 / 4 steps
1
DATA SETUP: Create the user profile data
Create a dictionary called user_profile with these exact entries: 'id': 101, 'name': 'Alice', 'email': 'alice@example.com'
Rest API
Hint
Use curly braces {} to create a dictionary with the exact keys and values.
2
CONFIGURATION: Create the ETag value
Create a variable called etag and set it to the string "abc123"
Rest API
Hint
Assign the string "abc123" to the variable etag.
3
CORE LOGIC: Write the get_user_profile function with validation-based caching
Write a function called get_user_profile that takes one parameter client_etag. Inside the function, if client_etag equals the variable etag, return the tuple (304, 'Not Modified'). Otherwise, return the tuple (200, user_profile).
Rest API
Hint
Use an if statement to compare client_etag and etag, then return the correct tuple.
4
OUTPUT: Call the function and print the result
Call the function get_user_profile with the argument "abc123" and print the result.
Rest API
Hint
Use print(get_user_profile("abc123")) to show the output.
Practice
(1/5)
1. What is the main purpose of validation-based caching in REST APIs?
easy
A. To encrypt data during transmission
B. To speed up the server response by skipping validation
C. To store data permanently on the client side
D. To check if the data has changed before downloading it again