Consider a REST API that uses idempotency keys to prevent duplicate resource creation. The client sends a POST request with an idempotency key header. The server stores the response for that key.
What will the server return if the client retries the same POST request with the same idempotency key?
POST /orders HTTP/1.1 Idempotency-Key: abc123 { "item": "book", "quantity": 1 } # Retry with the same Idempotency-Key: abc123
Think about why idempotency keys are used in APIs.
Idempotency keys ensure that retrying the same request does not create duplicate resources. The server returns the original response for the same key.
Which of the following best explains the main purpose of idempotency keys in REST APIs?
Think about what happens when a client retries a request due to network issues.
Idempotency keys let clients retry requests safely by ensuring the server processes the request only once, avoiding duplicate side effects.
Review the following pseudocode for handling POST requests with idempotency keys. What is the bug?
def handle_post(request): key = request.headers.get('Idempotency-Key') if key in cache: return cache[key] response = process_request(request) # Missing cache storage here return response
Think about what happens on the second request with the same key.
The code checks the cache but never stores the response after processing, so retries won't return the cached response.
Choose the code snippet that correctly stores and returns a cached response for an idempotency key.
cache = {}
def handle_request(request):
key = request.headers.get('Idempotency-Key')
if key in cache:
return cache[key]
response = process(request)
# Store response here
return responseRemember how to assign values to dictionary keys in Python.
Option C correctly assigns the response to the dictionary key. Other options use invalid syntax or methods.
A client sends these POST requests to the server with idempotency keys:
- POST with key 'x1'
- POST with key 'x2'
- POST with key 'x1' again (retry)
- POST with key 'x3'
- POST with key 'x2' again (retry)
Assuming the server correctly caches responses by idempotency key, how many unique responses are stored in the cache after these requests?
Count unique keys used in the requests.
There are three unique keys: 'x1', 'x2', and 'x3'. Retries do not add new entries.