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.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 12 views 0 copies

Python code

21 lines
Python 3.9+
import 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

stdout
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

  1. Use a decorator around a real HTTP client to inject the header automatically.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.