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.
  • Python 3.14 adds uuid.uuid6(), uuid.uuid7() and uuid.uuid8().
  • Use uuid.UUID(value) for parsing and validation.
  • Store UUID values consistently as native UUID columns or canonical strings.

For implementation context, continue with JavaScript, SQL, and UUID Validator. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.

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))

Generate UUID v7 in Python 3.14+

Python 3.14 adds native UUID v6, v7 and v8 generation. Use uuid.uuid7() when a time-ordered standard UUID fits your database or event workflow; keep uuid.uuid4() when you want an opaque random identifier.

import uuid

ordered_id = uuid.uuid7()
print(ordered_id)
print(ordered_id.time)  # creation time in milliseconds

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?

Yes in Python 3.14 and later with uuid.uuid7(). On older Python versions, 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