Module supertokens_python.types.response

Expand source code
# Copyright (c) 2025, VRAI Labs and/or its affiliates. All rights reserved.
#
# This software is licensed under the Apache License, Version 2.0 (the
# "License") as published by the Apache Software Foundation.
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from abc import ABC, abstractmethod
from typing import Any, Dict, Generic, Literal, Protocol, TypeVar, runtime_checkable

from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
from typing_extensions import Self

Status = TypeVar("Status", bound=str)
Reason = TypeVar("Reason", bound=str)


class APIResponse(ABC):
    @abstractmethod
    def to_json(self) -> Dict[str, Any]: ...


class GeneralErrorResponse(APIResponse):
    def __init__(self, message: str):
        self.status = "GENERAL_ERROR"
        self.message = message

    def to_json(self) -> Dict[str, Any]:
        return {"status": self.status, "message": self.message}


class CamelCaseBaseModel(APIResponse, BaseModel):
    model_config = ConfigDict(
        alias_generator=to_camel,
        populate_by_name=True,
        # Support interop between Pydantic and old classes
        arbitrary_types_allowed=True,
    )

    @classmethod
    def from_json(cls, obj: Dict[str, Any]) -> Self:
        """
        Converts a dictionary to a Pydantic model.
        """
        return cls.model_validate(obj)

    def to_json(self) -> Dict[str, Any]:
        """
        Converts the Pydantic model to a dictionary.
        """
        return self.model_dump(by_alias=True)


"""
Protocol classes will allow use of older classes with these new types
They're like interfaces and allow classes to be interpreted as per their properties,
instead of their actual types, allowing use with the `StatusResponse` types.

Issue: Generic Protocols require the generic to be `invariant` - types need to be exact
Types defined as `StatusResponse[Literal["A", "B"]]`, and only one of these is returned.
This requires the generic to be `covariant`, which is not allowed in Protocols.

Solution: Refactor the types to be `StatusResponse[Literal["A"]] | StatusResponse[Literal["B"]]`
"""


@runtime_checkable
class HasStatus(Protocol[Status]):
    status: Status


@runtime_checkable
class HasErr(Protocol[Status]):
    err: Status


@runtime_checkable
class HasReason(Protocol[Status]):
    reason: Status


class StatusResponseBaseModel(CamelCaseBaseModel, Generic[Status]):
    status: Status


class StatusReasonResponseBaseModel(
    StatusResponseBaseModel[Status], Generic[Status, Reason]
):
    reason: Reason


class OkResponseBaseModel(StatusResponseBaseModel[Literal["OK"]]):
    status: Literal["OK"] = "OK"


class StatusErrResponseBaseModel(StatusResponseBaseModel[Status]):
    err: str

Classes

class APIResponse

Helper class that provides a standard way to create an ABC using inheritance.

Expand source code
class APIResponse(ABC):
    @abstractmethod
    def to_json(self) -> Dict[str, Any]: ...

Ancestors

  • abc.ABC

Subclasses

Methods

def to_json(self) ‑> Dict[str, Any]
class CamelCaseBaseModel (**data: Any)

Helper class that provides a standard way to create an ABC using inheritance.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Expand source code
class CamelCaseBaseModel(APIResponse, BaseModel):
    model_config = ConfigDict(
        alias_generator=to_camel,
        populate_by_name=True,
        # Support interop between Pydantic and old classes
        arbitrary_types_allowed=True,
    )

    @classmethod
    def from_json(cls, obj: Dict[str, Any]) -> Self:
        """
        Converts a dictionary to a Pydantic model.
        """
        return cls.model_validate(obj)

    def to_json(self) -> Dict[str, Any]:
        """
        Converts the Pydantic model to a dictionary.
        """
        return self.model_dump(by_alias=True)

Ancestors

Subclasses

Class variables

var model_config

Static methods

def from_json(obj: Dict[str, Any]) ‑> Self

Converts a dictionary to a Pydantic model.

Methods

def to_json(self) ‑> Dict[str, Any]

Converts the Pydantic model to a dictionary.

class GeneralErrorResponse (message: str)

Helper class that provides a standard way to create an ABC using inheritance.

Expand source code
class GeneralErrorResponse(APIResponse):
    def __init__(self, message: str):
        self.status = "GENERAL_ERROR"
        self.message = message

    def to_json(self) -> Dict[str, Any]:
        return {"status": self.status, "message": self.message}

Ancestors

Methods

def to_json(self) ‑> Dict[str, Any]
class HasErr (*args, **kwargs)

Base class for protocol classes.

Protocol classes are defined as::

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).

For example::

class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check

See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as::

class GenProto[T](Protocol):
    def meth(self) -> T:
        ...
Expand source code
@runtime_checkable
class HasErr(Protocol[Status]):
    err: Status

Ancestors

  • typing.Protocol
  • typing.Generic

Class variables

var err : ~Status
class HasReason (*args, **kwargs)

Base class for protocol classes.

Protocol classes are defined as::

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).

For example::

class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check

See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as::

class GenProto[T](Protocol):
    def meth(self) -> T:
        ...
Expand source code
@runtime_checkable
class HasReason(Protocol[Status]):
    reason: Status

Ancestors

  • typing.Protocol
  • typing.Generic

Class variables

var reason : ~Status
class HasStatus (*args, **kwargs)

Base class for protocol classes.

Protocol classes are defined as::

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).

For example::

class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check

See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as::

class GenProto[T](Protocol):
    def meth(self) -> T:
        ...
Expand source code
@runtime_checkable
class HasStatus(Protocol[Status]):
    status: Status

Ancestors

  • typing.Protocol
  • typing.Generic

Class variables

var status : ~Status
class OkResponseBaseModel (**data: Any)

Helper class that provides a standard way to create an ABC using inheritance.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Expand source code
class OkResponseBaseModel(StatusResponseBaseModel[Literal["OK"]]):
    status: Literal["OK"] = "OK"

Ancestors

Subclasses

Class variables

var model_config
var status : Literal['OK']

Inherited members

class StatusErrResponseBaseModel (**data: Any)

Helper class that provides a standard way to create an ABC using inheritance.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Expand source code
class StatusErrResponseBaseModel(StatusResponseBaseModel[Status]):
    err: str

Ancestors

Subclasses

  • supertokens_python.types.response.StatusErrResponseBaseModel[Literal['INVALID_EMAIL_ERROR']]

Class variables

var err : str
var model_config

Inherited members

class StatusReasonResponseBaseModel (**data: Any)

Helper class that provides a standard way to create an ABC using inheritance.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Expand source code
class StatusReasonResponseBaseModel(
    StatusResponseBaseModel[Status], Generic[Status, Reason]
):
    reason: Reason

Ancestors

Subclasses

Class variables

var model_config
var reason : ~Reason

Inherited members

class StatusReasonResponseBaseModel[Literal['LINKING_TO_SESSION_USER_FAILED'], Literal['EMAIL_VERIFICATION_REQUIRED', 'RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR', 'ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR', 'SESSION_USER_ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR', 'INPUT_USER_IS_NOT_A_PRIMARY_USER']] (**data: Any)

Helper class that provides a standard way to create an ABC using inheritance.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Ancestors

Subclasses

Class variables

var model_config

Inherited members

class StatusResponseBaseModel (**data: Any)

Helper class that provides a standard way to create an ABC using inheritance.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Expand source code
class StatusResponseBaseModel(CamelCaseBaseModel, Generic[Status]):
    status: Status

Ancestors

Subclasses

  • StatusErrResponseBaseModel
  • StatusReasonResponseBaseModel
  • supertokens_python.types.response.StatusResponseBaseModel[Literal['CREDENTIAL_NOT_FOUND_ERROR']]
  • supertokens_python.types.response.StatusResponseBaseModel[Literal['EMAIL_ALREADY_EXISTS_ERROR']]
  • supertokens_python.types.response.StatusResponseBaseModel[Literal['INVALID_CREDENTIALS_ERROR']]
  • supertokens_python.types.response.StatusResponseBaseModel[Literal['INVALID_OPTIONS_ERROR']]
  • StatusResponseBaseModel[Literal['OK']]
  • supertokens_python.types.response.StatusResponseBaseModel[Literal['OPTIONS_NOT_FOUND_ERROR']]
  • supertokens_python.types.response.StatusResponseBaseModel[Literal['RECOVER_ACCOUNT_TOKEN_INVALID_ERROR']]
  • supertokens_python.types.response.StatusResponseBaseModel[Literal['UNKNOWN_USER_ID_ERROR']]

Class variables

var model_config
var status : ~Status

Inherited members

class StatusResponseBaseModel[Literal['OK']] (**data: Any)

Helper class that provides a standard way to create an ABC using inheritance.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Ancestors

Subclasses

Class variables

var model_config

Inherited members