0
0
Rest APIprogramming~20 mins

If-None-Match and 304 responses in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Using If-None-Match Header and 304 Responses in REST API
📖 Scenario: You are building a simple REST API that returns user profile data. To save bandwidth and improve speed, you want to use the If-None-Match header and 304 Not Modified responses.This means the client sends a version tag (ETag) it has, and the server checks if the data has changed. If not, the server replies with 304 and no data, telling the client to use its cached copy.
🎯 Goal: Build a REST API endpoint that returns user data with an ETag. It should check the If-None-Match header from the client and respond with 304 Not Modified if the data has not changed, or 200 OK with the data if it has changed.
📋 What You'll Learn
Create a dictionary called user_profile with keys name, age, and email and exact values 'Alice', 30, and 'alice@example.com' respectively.
Create a string variable called etag with the exact value "v1" representing the version of the data.
Write a function called handle_request that takes a parameter if_none_match (string or None). Inside, check if if_none_match equals etag. If yes, return a tuple (304, None). Otherwise, return (200, user_profile).
Call handle_request twice: once with if_none_match set to "v1" and once with None. Print the results exactly as shown.
💡 Why This Matters
🌍 Real World
Web servers use ETags and 304 responses to reduce bandwidth and speed up page loads by telling browsers when cached data is still valid.
💼 Career
Understanding HTTP caching headers like If-None-Match and 304 responses is important for backend developers building efficient REST APIs.
Progress0 / 4 steps
1
Create the user profile data
Create a dictionary called user_profile with these exact entries: 'name': 'Alice', 'age': 30, and 'email': 'alice@example.com'.
Rest API
Need a hint?
Use curly braces {} to create a dictionary with the exact keys and values.
2
Create the ETag version string
Create a string variable called etag and set it to the exact value "v1".
Rest API
Need a hint?
Use double quotes "v1" exactly for the etag string.
3
Write the request handler function
Write a function called handle_request that takes one parameter if_none_match. Inside, check if if_none_match == etag. If yes, return (304, None). Otherwise, return (200, user_profile).
Rest API
Need a hint?
Use an if-else statement to compare if_none_match with etag and return the correct tuple.
4
Call the function and print results
Call handle_request with if_none_match set to "v1" and print the result. Then call it with None and print the result.
Rest API
Need a hint?
Use print() to show the results of calling handle_request with "v1" and None.