Python includes a UUID module in the standard library. For most application IDs, uuid.uuid4 is the practical default. Validate user input by parsing it instead of trying to clean up every possible string by hand.
Key takeaways
- Use uuid.uuid4() for random UUIDs.
- Use uuid.UUID(value) for parsing and validation.
- Store UUID values consistently as native UUID columns or canonical strings.
Generate a UUID v4 in Python
The standard library keeps the common case pleasantly boring. Generate the value, convert it to a string for JSON, and keep the UUID object when your database driver supports it.
import uuid
record_id = uuid.uuid4()
print(record_id)
print(str(record_id))Validate a UUID string
Parsing is usually safer than writing your own validation rules. If Python can construct a UUID object from the input, you can then compare the canonical string if strict formatting matters.
import uuid
def is_uuid(value):
try:
parsed = uuid.UUID(str(value))
except (ValueError, TypeError, AttributeError):
return False
return str(parsed) == str(value).lower()UUIDs in Python APIs
Most JSON APIs should send UUIDs as strings. Keep the canonical lowercase hyphenated form unless a client has a documented reason to receive another format.
In frameworks such as FastAPI or Django, prefer the framework UUID field or converter. That keeps route parsing and error handling consistent.
Database notes
PostgreSQL has a native uuid type, which is usually better than varchar for UUID columns. If your ORM supports UUID fields, use them so application code and the database agree about valid values.
