Code guide

Generate UUIDs in Python

Use Python UUID examples for uuid4, validation, database storage and API output.

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.

FAQ

Generate UUIDs in Python questions

Does Python generate UUID v7?

The standard library support depends on the Python version. If your runtime does not provide v7, use a maintained package or generate v7 in your database or service layer.

Should Python UUIDs be strings in JSON?

Yes. JSON does not have a UUID type, so APIs commonly serialize UUID values as strings.

Can Python validate GUID strings?

Yes. The uuid.UUID parser can handle common UUID/GUID text values, including uppercase input.

Generate UUID in Python - uuid4 Examples and Validation