Skip to content

Web

Validated types for web standards: authentication tokens, MIME types, hashes, and network identifiers.

Modules:

  • auth

    Validated types for HTTP authentication headers.

  • hash

    Cryptographic hash hex digest types.

  • jwt

    JSON Web Token (JWT) type with parsed header and payload.

  • mime

    MIME type with parsed components.

  • network

    Validated types for network identifiers.

  • slug

    Validated type for URL slugs.

  • urn

    Validated type for Uniform Resource Names (URNs).

Classes:

  • BearerToken

    A Bearer token string like 'Bearer ' with the extracted token value.

  • Fqdn

    A fully qualified domain name like www.example.com with parsed labels.

  • Host

    A network host (domain name, IPv4, or bracketed IPv6) with a host_type property.

  • Jwt

    A JSON Web Token (JWT) string with parsed header and payload.

  • MimeType

    A MIME type like application/json or text/html;charset=utf-8.

  • PortRange

    A TCP/UDP port or port range like 443 or 8080-8090 with parsed endpoints.

  • Urn

    A Uniform Resource Name like urn:isbn:0451450523 with parsed NID and NSS.

Attributes:

  • Md5Hex

    An MD5 hex digest (32 hex characters, normalized to lowercase) (e.g. d41d8cd98f00b204e9800998ecf8427e).

  • Sha1Hex

    A SHA-1 hex digest (40 hex characters, normalized to lowercase) (e.g. da39a3ee5e6b4b0d3255bfef95601890afd80709).

  • Sha256Hex

    A SHA-256 hex digest (64 hex characters, normalized to lowercase) (e.g. e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855).

  • Slug

    A URL-friendly slug: lowercase alphanumeric with hyphens (e.g. my-blog-post).

Md5Hex module-attribute

Md5Hex = Annotated[str, AfterValidator(_validate_md5_hex), WithJsonSchema({'type': 'string', 'format': 'md5-hex', 'pattern': '^[0-9a-fA-F]{32}$', 'description': 'An MD5 hex digest (32 hex characters, normalized to lowercase)', 'examples': ['d41d8cd98f00b204e9800998ecf8427e'], 'title': 'Md5Hex', 'minLength': 32, 'maxLength': 32})]

An MD5 hex digest (32 hex characters, normalized to lowercase) (e.g. d41d8cd98f00b204e9800998ecf8427e).

Sha1Hex module-attribute

Sha1Hex = Annotated[str, AfterValidator(_validate_sha1_hex), WithJsonSchema({'type': 'string', 'format': 'sha1-hex', 'pattern': '^[0-9a-fA-F]{40}$', 'description': 'A SHA-1 hex digest (40 hex characters, normalized to lowercase)', 'examples': ['da39a3ee5e6b4b0d3255bfef95601890afd80709'], 'title': 'Sha1Hex', 'minLength': 40, 'maxLength': 40})]

A SHA-1 hex digest (40 hex characters, normalized to lowercase) (e.g. da39a3ee5e6b4b0d3255bfef95601890afd80709).

Sha256Hex module-attribute

Sha256Hex = Annotated[str, AfterValidator(_validate_sha256_hex), WithJsonSchema({'type': 'string', 'format': 'sha256-hex', 'pattern': '^[0-9a-fA-F]{64}$', 'description': 'A SHA-256 hex digest (64 hex characters, normalized to lowercase)', 'examples': ['e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'], 'title': 'Sha256Hex', 'minLength': 64, 'maxLength': 64})]

A SHA-256 hex digest (64 hex characters, normalized to lowercase) (e.g. e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855).

Slug module-attribute

Slug = Annotated[str, AfterValidator(_validate_slug), WithJsonSchema({'type': 'string', 'pattern': '^[a-z0-9]+(-[a-z0-9]+)*$', 'description': 'A URL-friendly slug: lowercase alphanumeric with hyphens', 'examples': ['my-blog-post', 'hello-world', 'pydantic-types-101'], 'title': 'Slug', 'maxLength': 128})]

A URL-friendly slug: lowercase alphanumeric with hyphens (e.g. my-blog-post).

BearerToken

Bases: str

A Bearer token string like 'Bearer ' with the extracted token value.

Methods:

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema

Return the Pydantic core schema for BearerToken.

Source code in src/pydantypes/web/auth.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Return the Pydantic core schema for BearerToken."""
    return _str_type_core_schema(cls, source_type, handler)

__get_pydantic_json_schema__ classmethod

__get_pydantic_json_schema__(_core_schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue

Return the JSON schema for BearerToken.

Source code in src/pydantypes/web/auth.py
@classmethod
def __get_pydantic_json_schema__(
    cls, _core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    """Return the JSON schema for BearerToken."""
    return {
        "type": "string",
        "format": "bearer-token",
        "pattern": cls._pattern.pattern,
        "description": "An HTTP Bearer token (RFC 6750)",
        "examples": ["Bearer eyJhbGciOiJIUzI1NiIs..."],
        "title": "BearerToken",
    }

__new__

__new__(value: str) -> BearerToken

Create and validate a new BearerToken instance.

Source code in src/pydantypes/web/auth.py
def __new__(cls, value: str) -> BearerToken:
    """Create and validate a new BearerToken instance."""
    m = cls._pattern.match(value)
    if not m:
        raise PydanticCustomError(
            "bearer_token",
            "Invalid Bearer token: {value}",
            {"value": value},
        )
    instance = str.__new__(cls, value)
    instance.token = m.group(1)
    return instance

Fqdn

Bases: str

A fully qualified domain name like www.example.com with parsed labels.

Methods:

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema

Return the Pydantic core schema for Fqdn.

Source code in src/pydantypes/web/network.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Return the Pydantic core schema for Fqdn."""
    return _str_type_core_schema(cls, source_type, handler)

__get_pydantic_json_schema__ classmethod

__get_pydantic_json_schema__(_core_schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue

Return the JSON schema for Fqdn.

Source code in src/pydantypes/web/network.py
@classmethod
def __get_pydantic_json_schema__(
    cls, _core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    """Return the JSON schema for Fqdn."""
    return {
        "type": "string",
        "format": "fqdn",
        "description": "A fully qualified domain name (RFC 1123, normalized to lowercase)",
        "examples": ["www.example.com", "api.github.com"],
        "title": "Fqdn",
        "maxLength": 253,
    }

__new__

__new__(value: str) -> Fqdn

Create and validate a new Fqdn instance.

Source code in src/pydantypes/web/network.py
def __new__(cls, value: str) -> Fqdn:
    """Create and validate a new Fqdn instance."""
    # Strip optional trailing dot (DNS absolute notation)
    normalized = value.rstrip(".")
    if not normalized:
        raise PydanticCustomError(
            "fqdn", "Invalid FQDN: must not be empty. Got: {value}", {"value": value}
        )
    if len(normalized) > 253:
        raise PydanticCustomError(
            "fqdn",
            "Invalid FQDN: total length must be <= 253. Got: {value}",
            {"value": value},
        )
    labels = normalized.split(".")
    if len(labels) < 2:
        raise PydanticCustomError(
            "fqdn",
            "Invalid FQDN: must have at least 2 labels. Got: {value}",
            {"value": value},
        )
    for label in labels:
        if not label or len(label) > 63:
            raise PydanticCustomError(
                "fqdn",
                "Invalid FQDN: each label must be 1-63 characters. Got: {value}",
                {"value": value},
            )
        if not _FQDN_LABEL_RE.match(label):
            raise PydanticCustomError(
                "fqdn",
                "Invalid FQDN: label contains invalid characters. Got: {value}",
                {"value": value},
            )
    normalized = normalized.lower()
    instance = str.__new__(cls, normalized)
    instance.labels = normalized.split(".")
    instance.tld = instance.labels[-1]
    return instance

Host

Bases: str

A network host (domain name, IPv4, or bracketed IPv6) with a host_type property.

Methods:

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema

Return the Pydantic core schema for Host.

Source code in src/pydantypes/web/network.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Return the Pydantic core schema for Host."""
    return _str_type_core_schema(cls, source_type, handler)

__get_pydantic_json_schema__ classmethod

__get_pydantic_json_schema__(_core_schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue

Return the JSON schema for Host.

Source code in src/pydantypes/web/network.py
@classmethod
def __get_pydantic_json_schema__(
    cls, _core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    """Return the JSON schema for Host."""
    return {
        "type": "string",
        "format": "host",
        "description": "A network host: domain name, IPv4 address, or bracketed IPv6 address (RFC 3986)",
        "examples": ["example.com", "192.168.1.1", "[::1]"],
        "title": "Host",
    }

__new__

__new__(value: str) -> Host

Create and validate a new Host instance.

Source code in src/pydantypes/web/network.py
def __new__(cls, value: str) -> Host:
    """Create and validate a new Host instance."""
    if not value:
        raise PydanticCustomError(
            "host", "Invalid host: must not be empty. Got: {value}", {"value": value}
        )

    # Try bracketed IPv6 first: [::1]
    if value.startswith("[") and value.endswith("]"):
        inner = value[1:-1]
        try:
            ipaddress.IPv6Address(inner)
        except ValueError as e:
            raise PydanticCustomError(
                "host",
                "Invalid host: not a valid bracketed IPv6 address. Got: {value}",
                {"value": value},
            ) from e
        instance = str.__new__(cls, value)
        instance.host_type = "ipv6"
        return instance

    # Try IPv4
    try:
        ipaddress.IPv4Address(value)
        instance = str.__new__(cls, value)
        instance.host_type = "ipv4"
        return instance
    except ValueError:
        pass

    # Try domain name
    if _DOMAIN_RE.match(value):
        normalized = value.lower()
        instance = str.__new__(cls, normalized)
        instance.host_type = "domain"
        return instance

    raise PydanticCustomError(
        "host",
        "Invalid host: not a valid domain name, IPv4, or bracketed IPv6 address. Got: {value}",
        {"value": value},
    )

Jwt

Bases: str

A JSON Web Token (JWT) string with parsed header and payload.

Methods:

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema

Return the Pydantic core schema for Jwt.

Source code in src/pydantypes/web/jwt.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Return the Pydantic core schema for Jwt."""
    return _str_type_core_schema(cls, source_type, handler)

__get_pydantic_json_schema__ classmethod

__get_pydantic_json_schema__(_core_schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue

Return the JSON schema for Jwt.

Source code in src/pydantypes/web/jwt.py
@classmethod
def __get_pydantic_json_schema__(
    cls, _core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    """Return the JSON schema for Jwt."""
    return {
        "type": "string",
        "format": "jwt",
        "description": (
            "A JSON Web Token (JWT) with three dot-separated base64url-encoded parts"
        ),
        "examples": [
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"
        ],
        "title": "Jwt",
    }

__new__

__new__(value: str) -> Jwt

Create and validate a new Jwt instance.

Source code in src/pydantypes/web/jwt.py
def __new__(cls, value: str) -> Jwt:
    """Create and validate a new Jwt instance."""
    parts = value.split(".")
    if len(parts) != 3:
        raise PydanticCustomError(
            "jwt",
            "Invalid JWT: expected 3 dot-separated parts. Got: {value}",
            {"value": value},
        )
    try:
        header = cls._decode_part(parts[0])
    except Exception as e:
        raise PydanticCustomError(
            "jwt",
            "Invalid JWT header: could not decode. Got: {value}",
            {"value": value},
        ) from e
    try:
        payload = cls._decode_part(parts[1])
    except Exception as e:
        raise PydanticCustomError(
            "jwt",
            "Invalid JWT payload: could not decode. Got: {value}",
            {"value": value},
        ) from e
    instance = str.__new__(cls, value)
    instance.header = header
    instance.payload = payload
    return instance

MimeType

Bases: str

A MIME type like application/json or text/html;charset=utf-8.

Methods:

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema

Return the Pydantic core schema for MimeType.

Source code in src/pydantypes/web/mime.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Return the Pydantic core schema for MimeType."""
    return _str_type_core_schema(cls, source_type, handler)

__get_pydantic_json_schema__ classmethod

__get_pydantic_json_schema__(_core_schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue

Return the JSON schema for MimeType.

Source code in src/pydantypes/web/mime.py
@classmethod
def __get_pydantic_json_schema__(
    cls, _core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    """Return the JSON schema for MimeType."""
    return {
        "type": "string",
        "format": "mime-type",
        "pattern": cls._pattern.pattern,
        "description": "A MIME type like application/json or text/html;charset=utf-8",
        "examples": ["application/json", "text/html;charset=utf-8"],
        "title": "MimeType",
    }

__new__

__new__(value: str) -> MimeType

Create and validate a new MimeType instance.

Source code in src/pydantypes/web/mime.py
def __new__(cls, value: str) -> MimeType:
    """Create and validate a new MimeType instance."""
    m = cls._pattern.match(value)
    if not m:
        raise PydanticCustomError(
            "mime_type",
            "Invalid MIME type: {value}",
            {"value": value},
        )
    instance = str.__new__(cls, value)
    instance.type = m.group("type")
    instance.subtype = m.group("subtype")
    params_str = m.group("params") or ""
    params: dict[str, str] = {}
    if params_str:
        for param in params_str.split(";"):
            param = param.strip()
            if not param:
                continue
            if "=" in param:
                k, v_param = param.split("=", 1)
                params[k.strip()] = v_param.strip()
    instance.parameters = params
    return instance

PortRange

Bases: str

A TCP/UDP port or port range like 443 or 8080-8090 with parsed endpoints.

Methods:

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema

Return the Pydantic core schema for PortRange.

Source code in src/pydantypes/web/network.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Return the Pydantic core schema for PortRange."""
    return _str_type_core_schema(cls, source_type, handler)

__get_pydantic_json_schema__ classmethod

__get_pydantic_json_schema__(_core_schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue

Return the JSON schema for PortRange.

Source code in src/pydantypes/web/network.py
@classmethod
def __get_pydantic_json_schema__(
    cls, _core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    """Return the JSON schema for PortRange."""
    return {
        "type": "string",
        "format": "port-range",
        "pattern": cls._pattern.pattern,
        "description": "A TCP/UDP port (0-65535) or port range like 8080-8090",
        "examples": ["443", "8080-8090", "0"],
        "title": "PortRange",
    }

__new__

__new__(value: str) -> PortRange

Create and validate a new PortRange instance.

Source code in src/pydantypes/web/network.py
def __new__(cls, value: str) -> PortRange:
    """Create and validate a new PortRange instance."""
    m = cls._pattern.match(value)
    if not m:
        raise PydanticCustomError(
            "port_range",
            "Invalid port range: {value}",
            {"value": value},
        )
    start = int(m.group("start"))
    end_str = m.group("end")
    end = int(end_str) if end_str else start
    if start > 65535:
        raise PydanticCustomError(
            "port_range",
            "Invalid port range: port must be 0-65535. Got: {value}",
            {"value": value},
        )
    if end > 65535:
        raise PydanticCustomError(
            "port_range",
            "Invalid port range: port must be 0-65535. Got: {value}",
            {"value": value},
        )
    if start > end:
        raise PydanticCustomError(
            "port_range",
            "Invalid port range: start must be <= end. Got: {value}",
            {"value": value},
        )
    instance = str.__new__(cls, value)
    instance.start = start
    instance.end = end
    return instance

Urn

Bases: str

A Uniform Resource Name like urn:isbn:0451450523 with parsed NID and NSS.

Methods:

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema

Return the Pydantic core schema for Urn.

Source code in src/pydantypes/web/urn.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Return the Pydantic core schema for Urn."""
    return _str_type_core_schema(cls, source_type, handler)

__get_pydantic_json_schema__ classmethod

__get_pydantic_json_schema__(_core_schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue

Return the JSON schema for Urn.

Source code in src/pydantypes/web/urn.py
@classmethod
def __get_pydantic_json_schema__(
    cls, _core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
    """Return the JSON schema for Urn."""
    return {
        "type": "string",
        "format": "urn",
        "pattern": cls._pattern.pattern,
        "description": "A Uniform Resource Name (RFC 8141) in the format urn:NID:NSS",
        "examples": ["urn:isbn:0451450523", "urn:ietf:rfc:2648", "urn:oid:2.16.840"],
        "title": "Urn",
    }

__new__

__new__(value: str) -> Urn

Create and validate a new Urn instance.

Source code in src/pydantypes/web/urn.py
def __new__(cls, value: str) -> Urn:
    """Create and validate a new Urn instance."""
    m = cls._pattern.match(value)
    if not m:
        raise PydanticCustomError(
            "urn",
            "Invalid URN: {value}",
            {"value": value},
        )
    nid = m.group("nid")
    if nid.lower().startswith("urn-"):
        raise PydanticCustomError(
            "urn",
            "Invalid URN: NID must not start with 'urn-'. Got: {value}",
            {"value": value},
        )
    instance = str.__new__(cls, value)
    instance.nid = nid.lower()
    instance.nss = m.group("nss")
    instance.r_component = m.group("r_component")
    instance.q_component = m.group("q_component")
    instance.f_component = m.group("f_component")
    return instance