0
0
Rest APIprogramming~30 mins

Response headers (Cache-Control, ETag) in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Response headers (Cache-Control, ETag)
📖 Scenario: You are building a simple REST API that returns product information. To improve performance and reduce unnecessary data transfer, you want to add HTTP response headers Cache-Control and ETag.The Cache-Control header tells browsers how long they can keep the response before asking again. The ETag header helps browsers check if the data has changed since last time.
🎯 Goal: Create a REST API endpoint that returns product data with Cache-Control and ETag headers set correctly.
📋 What You'll Learn
Create a dictionary called product with keys id, name, and price with values 101, "Coffee Mug", and 12.99 respectively.
Create a variable called cache_duration and set it to 3600 (seconds).
Create a function called generate_etag that takes the product dictionary and returns a string ETag by hashing the string representation of the product.
Print the response headers Cache-Control with value max-age=3600 and ETag with the generated ETag.
💡 Why This Matters
🌍 Real World
Response headers like <code>Cache-Control</code> and <code>ETag</code> help browsers and servers communicate efficiently. They reduce bandwidth and speed up loading times by avoiding sending unchanged data.
💼 Career
Understanding and setting HTTP headers is important for backend developers, API developers, and web engineers to optimize web performance and caching strategies.
Progress0 / 4 steps
1
DATA SETUP: Create the product dictionary
Create a dictionary called product with these exact entries: 'id': 101, 'name': "Coffee Mug", and 'price': 12.99.
Rest API
Need a hint?

Use curly braces {} to create a dictionary with the exact keys and values.

2
CONFIGURATION: Set cache duration
Create a variable called cache_duration and set it to 3600 (seconds).
Rest API
Need a hint?

Just assign the number 3600 to the variable cache_duration.

3
CORE LOGIC: Create the ETag generator function
Create a function called generate_etag that takes the product dictionary as input and returns a string ETag by hashing the string representation of product using the hashlib.md5 function.
Rest API
Need a hint?

Use str(product) to convert the dictionary to a string, then encode it and hash with hashlib.md5. Return the hex digest.

4
OUTPUT: Print the response headers
Print the response headers Cache-Control with value max-age=3600 and ETag with the generated ETag from generate_etag(product). Use the exact print statements: print(f"Cache-Control: max-age={cache_duration}") and print(f"ETag: {etag}").
Rest API
Need a hint?

Call generate_etag(product) and store it in etag. Then print the headers exactly as shown.