Generate an Idempotency-Key header mock with UUID in Python
This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.
Python code
21 linesimport uuid
class MockIdempotencyService:
def __init__(self):
self._tokens = {}
def get_token(self, header_name="Idempotency-Key"):
token = str(uuid.uuid4())
self._tokens[header_name] = token
return token
def validate(self, header_name="Idempotency-Key"):
return self._tokens.get(header_name)
if __name__ == "__main__":
service = MockIdempotencyService()
token = service.get_token()
print(f"Generated mock header: {token}")
print(f"Validated: {service.validate()}")
print(f"Same token on repeat call: {service.get_token() == token}")
Output
Generated mock header: 2c133f4e-7e6a-4b5a-8e6f-3c4d5e6f7a8b
Validated: 2c133f4e-7e6a-4b5a-8e6f-3c4d5e6f7a8b
Same token on repeat call: False
How it works
The uuid.uuid4() call generates a random, unique token that mimics real-world idempotency keys. The service stores the token in a dictionary, allowing later retrieval and validation. Each call to get_token creates a new token, so repeat calls return different values—expected behavior for idempotency semantics. The validate method returns the token if present, otherwise None, making it straightforward to check in production flows.
Common mistakes
- Using `uuid.uuid1()` instead of `uuid.uuid4()` can leak MAC address and timestamp, harming uniqueness privacy.
- Not storing tokens in a persistent store will lose idempotency across service restarts.
- Treating the mock as stateless when it actually maintains an internal dictionary.
Variations
- Use a decorator around a real HTTP client to inject the header automatically.
- Generate the token from a hash of the request payload to ensure same-input same-token.
Real-world use cases
- Mocking payment gateway idempotency keys during integration tests without network calls.
- Simulating idempotent API behavior in development to test duplicate request handling.
- Generating unique request identifiers for distributed tracing across microservices.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.