Skip to content

Response class

esmerald.Response

Response(content, *, status_code=status.HTTP_200_OK, media_type=MediaType.JSON, background=None, headers=None, cookies=None)

Bases: Response, Generic[T]

Default Response object from Esmerald where it can be as the return annotation of a handler.

Esmerakd automatically will understand what time of response is going to be used and parse all the details automatically.

Example

from pydantic import BaseModel

from esmerald import Esmerald, Gateway, Response, get
from esmerald.datastructures import Cookie


@get(path="/me")
async def home() -> Response:
    return Response(
        Item(id=1, sku="sku1238"),
        headers={"SKY-HEADER": "sku-xyz"},
        cookies=[Cookie(key="sku", value="a-value")],
    )


Esmerald(routes=[Gateway(handler=home)])
PARAMETER DESCRIPTION
content

Any content being sent to the response.

TYPE: Any

status_code

The response status code.

TYPE: int DEFAULT: HTTP_200_OK

media_type

The media type used in the response.

TYPE: Optional[Union[MediaType, str]] DEFAULT: JSON

background

TYPE: Optional[Union[BackgroundTask, BackgroundTasks]] DEFAULT: None

headers

Any additional headers being passed to the response.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import Response
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

Response(response_cookies=response_cookies)

TYPE: Optional[ResponseCookies] DEFAULT: None

Source code in esmerald/responses/base.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def __init__(
    self,
    content: Annotated[
        Any,
        Doc(
            """
            Any content being sent to the response.
            """
        ),
    ],
    *,
    status_code: Annotated[
        int,
        Doc(
            """
            The response status code.
            """
        ),
    ] = status.HTTP_200_OK,
    media_type: Annotated[
        Optional[Union["MediaType", str]],
        Doc(
            """
            The media type used in the response.
            """
        ),
    ] = MediaType.JSON,
    background: Annotated[
        Optional[Union["BackgroundTask", "BackgroundTasks"]],
        Doc(
            """
            Any instance of a [BackgroundTask or BackgroundTasks](https://esmerald.dev/background-tasks/).
            """
        ),
    ] = None,
    headers: Annotated[
        Optional[Dict[str, Any]],
        Doc(
            """
            Any additional headers being passed to the response.
            """
        ),
    ] = None,
    cookies: Annotated[
        Optional["ResponseCookies"],
        Doc(
            """
            A sequence of `esmerald.datastructures.Cookie` objects.

            Read more about the [Cookies](https://esmerald.dev/extras/cookie-fields/?h=responsecook#cookie-from-response-cookies).

            **Example**

            ```python
            from esmerald import Response
            from esmerald.datastructures import Cookie

            response_cookies=[
                Cookie(
                    key="csrf",
                    value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
                    max_age=3000,
                    httponly=True,
                )
            ]

            Response(response_cookies=response_cookies)
            ```
            """
        ),
    ] = None,
) -> None:
    super().__init__(
        content=content,
        status_code=status_code,
        headers=headers or {},
        media_type=media_type,
        background=cast("BackgroundTask", background),
    )
    self.cookies = cookies or []

media_type class-attribute instance-attribute

media_type = None

charset class-attribute instance-attribute

charset = 'utf-8'

status_code instance-attribute

status_code = status_code

background instance-attribute

background = background

body instance-attribute

body = self.render(content)

headers property

headers

cookies instance-attribute

cookies = cookies or []

init_headers

init_headers(headers=None)
PARAMETER DESCRIPTION
headers

TYPE: Optional[Mapping[str, str]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/responses.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def init_headers(
    self, headers: typing.Optional[typing.Mapping[str, str]] = None
) -> None:
    if headers is None:
        raw_headers: typing.List[typing.Tuple[bytes, bytes]] = []
        populate_content_length = True
        populate_content_type = True
    else:
        raw_headers = [
            (k.lower().encode("latin-1"), v.encode("latin-1"))
            for k, v in headers.items()
        ]
        keys = [h[0] for h in raw_headers]
        populate_content_length = b"content-length" not in keys
        populate_content_type = b"content-type" not in keys

    body = getattr(self, "body", None)
    if (
        body is not None
        and populate_content_length
        and not (self.status_code < 200 or self.status_code in (204, 304))
    ):
        content_length = str(len(body))
        raw_headers.append((b"content-length", content_length.encode("latin-1")))

    content_type = self.media_type
    if content_type is not None and populate_content_type:
        if content_type.startswith("text/"):
            content_type += "; charset=" + self.charset
        raw_headers.append((b"content-type", content_type.encode("latin-1")))

    self.raw_headers = raw_headers
set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite='lax')
PARAMETER DESCRIPTION
key

TYPE: str

value

TYPE: str DEFAULT: ''

max_age

TYPE: Optional[int] DEFAULT: None

expires

TYPE: Optional[Union[datetime, str, int]] DEFAULT: None

path

TYPE: str DEFAULT: '/'

domain

TYPE: Optional[str] DEFAULT: None

secure

TYPE: bool DEFAULT: False

httponly

TYPE: bool DEFAULT: False

samesite

TYPE: Optional[Literal['lax', 'strict', 'none']] DEFAULT: 'lax'

Source code in .venv/lib/python3.8/site-packages/starlette/responses.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def set_cookie(
    self,
    key: str,
    value: str = "",
    max_age: typing.Optional[int] = None,
    expires: typing.Optional[typing.Union[datetime, str, int]] = None,
    path: str = "/",
    domain: typing.Optional[str] = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Optional[typing.Literal["lax", "strict", "none"]] = "lax",
) -> None:
    cookie: "http.cookies.BaseCookie[str]" = http.cookies.SimpleCookie()
    cookie[key] = value
    if max_age is not None:
        cookie[key]["max-age"] = max_age
    if expires is not None:
        if isinstance(expires, datetime):
            cookie[key]["expires"] = format_datetime(expires, usegmt=True)
        else:
            cookie[key]["expires"] = expires
    if path is not None:
        cookie[key]["path"] = path
    if domain is not None:
        cookie[key]["domain"] = domain
    if secure:
        cookie[key]["secure"] = True
    if httponly:
        cookie[key]["httponly"] = True
    if samesite is not None:
        assert samesite.lower() in [
            "strict",
            "lax",
            "none",
        ], "samesite must be either 'strict', 'lax' or 'none'"
        cookie[key]["samesite"] = samesite
    cookie_val = cookie.output(header="").strip()
    self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
delete_cookie(key, path='/', domain=None, secure=False, httponly=False, samesite='lax')
PARAMETER DESCRIPTION
key

TYPE: str

path

TYPE: str DEFAULT: '/'

domain

TYPE: Optional[str] DEFAULT: None

secure

TYPE: bool DEFAULT: False

httponly

TYPE: bool DEFAULT: False

samesite

TYPE: Optional[Literal['lax', 'strict', 'none']] DEFAULT: 'lax'

Source code in .venv/lib/python3.8/site-packages/starlette/responses.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: typing.Optional[str] = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: typing.Optional[typing.Literal["lax", "strict", "none"]] = "lax",
) -> None:
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

transform staticmethod

transform(value)

The transformation of the data being returned.

It supports Pydantic models, dataclasses and msgspec.Struct.

PARAMETER DESCRIPTION
value

TYPE: Any

Source code in esmerald/responses/base.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
@staticmethod
def transform(value: Any) -> Dict[str, Any]:
    """
    The transformation of the data being returned.

    It supports Pydantic models, `dataclasses` and `msgspec.Struct`.
    """
    if isinstance(value, BaseModel):
        return value.model_dump()
    if is_dataclass(value):
        return dataclasses.asdict(value)
    if isinstance(value, msgspec.Struct):
        return msgspec.structs.asdict(value)
    raise TypeError("unsupported type")  # pragma: no cover

render

render(content)
PARAMETER DESCRIPTION
content

TYPE: Any

Source code in esmerald/responses/base.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def render(self, content: Any) -> bytes:
    try:
        if (
            content is None
            or content is NoReturn
            and (
                self.status_code < 100
                or self.status_code
                in {status.HTTP_204_NO_CONTENT, status.HTTP_304_NOT_MODIFIED}
            )
        ):
            return b""
        if self.media_type == MediaType.JSON:
            return dumps(
                content,
                default=self.transform,
                option=OPT_SERIALIZE_NUMPY | OPT_OMIT_MICROSECONDS,
            )
        return super().render(content)
    except (AttributeError, ValueError, TypeError) as e:  # pragma: no cover
        raise ImproperlyConfigured("Unable to serialize response content") from e