📖 Scenario: You are building a simple REST API that processes payment requests. Sometimes, clients may retry the same request if they don't get a response quickly. To avoid charging twice, your API needs to handle these retries safely.
🎯 Goal: Build a REST API endpoint that uses idempotency_key to ensure repeated requests with the same key do not cause duplicate processing.
📋 What You'll Learn
Create a dictionary to store processed idempotency keys and their results
Add a variable to hold the current request's idempotency key
Use logic to check if the idempotency key was seen before and return the stored result if yes
Print the final response for the request
💡 Why This Matters
🌍 Real World
Idempotency keys are used in payment systems and APIs to prevent duplicate charges or actions when clients retry requests due to network issues.
💼 Career
Understanding idempotency keys is important for backend developers and API designers to build reliable and safe services.
Progress0 / 4 steps
1
Create storage for processed requests
Create a dictionary called processed_requests that will store idempotency keys as keys and their results as values.
Rest API
Hint
Use curly braces {} to create an empty dictionary.
2
Add current request's idempotency key
Create a variable called idempotency_key and set it to the string 'abc123' to represent the current request's unique key.
Rest API
Hint
Use quotes to create a string value.
3
Check and store result using idempotency key
Write an if statement to check if idempotency_key is in processed_requests. If yes, set result to the stored value. Otherwise, set result to 'Payment processed' and store it in processed_requests with the key idempotency_key.
Rest API
Hint
Use if key in dict to check presence, and dictionary assignment to store values.
4
Print the final result
Write a print statement to display the value of result.
Rest API
Hint
Use print(result) to show the output.
Practice
(1/5)
1. What is the main purpose of using an idempotency key in REST APIs?
easy
A. To speed up the server response time
B. To prevent duplicate processing of the same request
C. To encrypt the request data
D. To authenticate the user
Solution
Step 1: Understand idempotency key concept
An idempotency key is a unique identifier sent with a request to ensure the server processes it only once.
Step 2: Identify the main purpose
This prevents duplicate actions like double payments or repeated orders if the client retries the request.
Final Answer:
To prevent duplicate processing of the same request -> Option B
B. process_data output for order1, None, process_data output for order2
C. process_data output for order1, process_data output for order2, process_data output for order2
D. process_data output for order1, process_data output for order1, process_data output for order2
Solution
Step 1: Analyze first call with key 'abc123'
Key not in stored_keys, so process_data('order1') runs, result saved and returned.
Step 2: Analyze second call with same key 'abc123'
Key found, stored response returned without reprocessing.
Step 3: Analyze third call with new key 'xyz789'
Key not found, process_data('order2') runs, result saved and returned.
Final Answer:
process_data output for order1, process_data output for order1, process_data output for order2 -> Option D
Quick Check:
Repeated key returns cached response [OK]
Hint: Repeated keys return cached response, new keys process data [OK]
Common Mistakes:
Assuming second call reprocesses data
Confusing keys and responses
Thinking None is returned on repeats
4. A developer wrote this code snippet to handle idempotent POST requests:
cache = {}
def post_request(key, data):
if key not in cache:
process(data)
return cache[key]
What is the bug in this code?
medium
A. It never stores the processed result in cache
B. It processes data twice for the same key
C. It raises an error if key is missing
D. It uses the wrong HTTP method
Solution
Step 1: Check caching logic
The code checks if key not in cache, then calls process(data), but never saves the result in cache.
Step 2: Identify consequence
Since cache[key] is never set, returning cache[key] will cause a KeyError or return None incorrectly.
Final Answer:
It never stores the processed result in cache -> Option A
Quick Check:
Missing cache storage causes errors [OK]
Hint: Always save processed result in cache before returning [OK]
Common Mistakes:
Assuming process(data) stores result automatically
Ignoring missing cache assignment
Thinking HTTP method affects caching here
5. You are designing a payment API that uses idempotency keys to avoid duplicate charges. Which approach best ensures safe retries without charging twice if the client resends the same request due to a timeout?
hard
A. Ignore the idempotency key and process every request independently
B. Reject any request with an idempotency key that was seen before
C. Store the payment result linked to the idempotency key and return it on repeated requests
D. Process the payment again but log a warning for duplicate keys
Solution
Step 1: Understand safe retry requirements
Safe retries mean the client can resend the same request without causing duplicate charges.
Step 2: Evaluate options
Store the payment result linked to the idempotency key and return it on repeated requests stores the payment result linked to the key and returns it on repeats, preventing double charges. Ignore the idempotency key and process every request independently processes every request, risking duplicates. Reject any request with an idempotency key that was seen before rejects repeats, which may cause client errors. Process the payment again but log a warning for duplicate keys processes again, causing duplicates.
Final Answer:
Store the payment result linked to the idempotency key and return it on repeated requests -> Option C
Quick Check:
Store and reuse result for idempotency [OK]
Hint: Save and reuse payment result by key to avoid duplicates [OK]
Common Mistakes:
Rejecting repeated keys causing client errors
Processing duplicates causing double charges
Logging warnings but still charging twice
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.