Skip to content

Response class

esmerald.Response

Response(content, *, status_code=HTTP_200_OK, media_type=None, background=None, headers=None, cookies=None, encoders=None)

Bases: ORJSONTransformMixin, 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: None

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(cookies=response_cookies)

TYPE: Optional[ResponseCookies] DEFAULT: None

encoders

A sequence of esmerald.encoders.Encoder type of objects to be used by the response object directly.

Example

from esmerald import Response
from esmerald.encoders import PydanticEncoder, MsgSpecEncoder

response_cookies=[
    encoders=[PydanticEncoder, MsgSpecEncoder]
]

Response(cookies=response_cookies)

TYPE: Union[Sequence[Encoder], None] DEFAULT: None

Source code in esmerald/responses/base.py
 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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.
            """
        ),
    ] = None,
    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(cookies=response_cookies)
            ```
            """
        ),
    ] = None,
    encoders: Annotated[
        Union[Sequence[Encoder], None],
        Doc(
            """
            A sequence of `esmerald.encoders.Encoder` type of objects to be used
            by the response object directly.

            **Example**

            ```python
            from esmerald import Response
            from esmerald.encoders import PydanticEncoder, MsgSpecEncoder

            response_cookies=[
                encoders=[PydanticEncoder, MsgSpecEncoder]
            ]

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

media_type class-attribute instance-attribute

media_type = None

status_code class-attribute instance-attribute

status_code = None

charset class-attribute instance-attribute

charset = 'utf-8'

passthrough_body_types class-attribute instance-attribute

passthrough_body_types = (bytes)

headers instance-attribute

headers

background instance-attribute

background = background

encoders instance-attribute

encoders = [encoder() if isclass(encoder) else encoder for encoder in encoders or _empty]

body instance-attribute

body = make_response(content)

encoded_headers property

encoded_headers

raw_headers class-attribute instance-attribute

raw_headers = encoded_headers

cookies instance-attribute

cookies = cookies or []

with_transform_kwargs classmethod

with_transform_kwargs(params)
PARAMETER DESCRIPTION
params

TYPE: dict | None

Source code in lilya/responses.py
92
93
94
95
96
97
98
99
@classmethod
@contextlib.contextmanager
def with_transform_kwargs(cls, params: dict | None, /) -> Generator[None, None, None]:
    token = RESPONSE_TRANSFORM_KWARGS.set(params)
    try:
        yield
    finally:
        RESPONSE_TRANSFORM_KWARGS.reset(token)

transform classmethod

transform(value)

The transformation of the data being returned (simplify operation).

Supports all the default encoders from Lilya and custom from Esmerald.

PARAMETER DESCRIPTION
value

TYPE: Any

Source code in esmerald/responses/mixins.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@classmethod
def transform(cls, value: Any) -> Any:
    """
    The transformation of the data being returned (simplify operation).

    Supports all the default encoders from Lilya and custom from Esmerald.
    """
    transform_kwargs = RESPONSE_TRANSFORM_KWARGS.get()
    if transform_kwargs is None:
        transform_kwargs = {}
    else:
        transform_kwargs.copy()
    transform_kwargs.setdefault(
        "json_encode_fn",
        partial(
            orjson.dumps, option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS
        ),
    )
    transform_kwargs.setdefault("post_transform_fn", orjson.loads)

    with cls.with_transform_kwargs(transform_kwargs):
        return super().transform(value)  # type: ignore

make_headers

make_headers(content_headers=None)

Initializes the headers based on RFC specifications by setting appropriate conditions and restrictions.

PARAMETER DESCRIPTION
content_headers

TYPE: Mapping[str, str] | dict[str, str] | None DEFAULT: None

PARAMETER DESCRIPTION
content_headers

Additional headers to include (default is None).

TYPE: Union[Mapping[str, str], Dict[str, str], None] DEFAULT: None

Source code in lilya/responses.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def make_headers(
    self, content_headers: Mapping[str, str] | dict[str, str] | None = None
) -> None:
    """
    Initializes the headers based on RFC specifications by setting appropriate conditions and restrictions.

    Args:
        content_headers (Union[Mapping[str, str], Dict[str, str], None], optional): Additional headers to include (default is None).
    """
    headers: dict[str, str] = {} if content_headers is None else content_headers  # type: ignore

    if HeaderHelper.has_entity_header_status(self.status_code):
        headers = HeaderHelper.remove_entity_headers(headers)
    if HeaderHelper.has_body_message(self.status_code):
        content_type = HeaderHelper.get_content_type(
            charset=self.charset, media_type=self.media_type
        )
        if hasattr(self, "body") and self.body is not None:
            headers.setdefault("content-length", str(len(self.body)))

        # Populates the content type if exists
        if content_type is not None:
            headers.setdefault("content-type", content_type)
    self.headers = Header(headers)
set_cookie(key, value='', *, path='/', domain=None, secure=False, max_age=None, expires=None, httponly=False, samesite='lax')

Sets a cookie in the response headers.

PARAMETER DESCRIPTION
key

TYPE: str

value

TYPE: str DEFAULT: ''

path

TYPE: str DEFAULT: '/'

domain

TYPE: str | None DEFAULT: None

secure

TYPE: bool DEFAULT: False

max_age

TYPE: int | None DEFAULT: None

expires

TYPE: datetime | str | int | None DEFAULT: None

httponly

TYPE: bool DEFAULT: False

samesite

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

PARAMETER DESCRIPTION
key

The name of the cookie.

TYPE: str

value

The value of the cookie.

TYPE: str DEFAULT: ''

path

The path for which the cookie is valid (default is '/').

TYPE: str DEFAULT: '/'

domain

The domain to which the cookie belongs.

TYPE: Union[str, None] DEFAULT: None

secure

If True, the cookie should only be sent over HTTPS.

TYPE: bool DEFAULT: False

max_age

The maximum age of the cookie in seconds.

TYPE: Union[int, None] DEFAULT: None

expires

The expiration date of the cookie.

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

httponly

If True, the cookie should only be accessible through HTTP.

TYPE: bool DEFAULT: False

samesite

SameSite attribute of the cookie.

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

RAISES DESCRIPTION
AssertionError

If samesite is not one of 'strict', 'lax', or 'none'.

Source code in lilya/responses.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def set_cookie(
    self,
    key: str,
    value: str = "",
    *,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    max_age: int | None = None,
    expires: datetime | str | int | None = None,
    httponly: bool = False,
    samesite: Literal["lax", "strict", "none"] = "lax",
) -> None:
    """
    Sets a cookie in the response headers.

    Args:
        key (str): The name of the cookie.
        value (str, optional): The value of the cookie.
        path (str, optional): The path for which the cookie is valid (default is '/').
        domain (Union[str, None], optional): The domain to which the cookie belongs.
        secure (bool, optional): If True, the cookie should only be sent over HTTPS.
        max_age (Union[int, None], optional): The maximum age of the cookie in seconds.
        expires (Union[Union[datetime, str, int], None], optional): The expiration date of the cookie.
        httponly (bool, optional): If True, the cookie should only be accessible through HTTP.
        samesite (Literal["lax", "strict", "none"], optional): SameSite attribute of the cookie.

    Raises:
        AssertionError: If samesite is not one of 'strict', 'lax', or '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.headers.add("set-cookie", cookie_val)
delete_cookie(key, path='/', domain=None, secure=False, httponly=False, samesite='lax')

Deletes a cookie in the response headers by setting its max age and expiration to 0.

PARAMETER DESCRIPTION
key

TYPE: str

path

TYPE: str DEFAULT: '/'

domain

TYPE: str | None DEFAULT: None

secure

TYPE: bool DEFAULT: False

httponly

TYPE: bool DEFAULT: False

samesite

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

PARAMETER DESCRIPTION
key

The name of the cookie to delete.

TYPE: str

path

The path for which the cookie is valid (default is '/').

TYPE: str DEFAULT: '/'

domain

The domain to which the cookie belongs.

TYPE: Union[str, None] DEFAULT: None

secure

If True, the cookie should only be sent over HTTPS.

TYPE: bool DEFAULT: False

httponly

If True, the cookie should only be accessible through HTTP.

TYPE: bool DEFAULT: False

samesite

SameSite attribute of the cookie.

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

Source code in lilya/responses.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def delete_cookie(
    self,
    key: str,
    path: str = "/",
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: Literal["lax", "strict", "none"] = "lax",
) -> None:
    """
    Deletes a cookie in the response headers by setting its max age and expiration to 0.

    Args:
        key (str): The name of the cookie to delete.
        path (str, optional): The path for which the cookie is valid (default is '/').
        domain (Union[str, None], optional): The domain to which the cookie belongs.
        secure (bool, optional): If True, the cookie should only be sent over HTTPS.
        httponly (bool, optional): If True, the cookie should only be accessible through HTTP.
        samesite (Literal["lax", "strict", "none"], optional): SameSite attribute of the cookie.
    """
    self.set_cookie(
        key,
        max_age=0,
        expires=0,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

message

message(prefix)
PARAMETER DESCRIPTION
prefix

TYPE: str

Source code in lilya/responses.py
266
267
268
269
270
271
272
def message(self, prefix: str) -> dict[str, Any]:
    return {
        "type": prefix + "http.response.start",
        "status": self.status_code,
        # some tests add headers dirty and assume a list
        "headers": self.headers.get_encoded_multi_items(),
    }

make_response

make_response(content)
PARAMETER DESCRIPTION
content

TYPE: Any

Source code in esmerald/responses/base.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def make_response(self, content: Any) -> bytes | memoryview | str:
    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""
    transform_kwargs = RESPONSE_TRANSFORM_KWARGS.get()
    if transform_kwargs:
        transform_kwargs = transform_kwargs.copy()
    elif isinstance(content, str) and self.media_type != MediaType.JSON:
        # treat strings special when not using json and disable mangling when no context is active.
        transform_kwargs = None
    else:
        transform_kwargs = {}
    if transform_kwargs is not None:
        transform_kwargs.setdefault(
            "json_encode_fn",
            partial(
                orjson.dumps,
                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,
            ),
        )
    try:
        # switch to a special mode for MediaType.JSON (default handlers)
        if self.media_type == MediaType.JSON:
            # keep it a serialized json object
            if transform_kwargs is not None:
                transform_kwargs.setdefault("post_transform_fn", None)
        # otherwise use default logic of lilya striping '"'
        with self.with_transform_kwargs(transform_kwargs):
            # if content is bytes it won't be transformed and
            # if None or NoReturn, return b"", this differs from the dedicated JSONResponses.
            return super().make_response(content)
    except (AttributeError, ValueError, TypeError) as e:  # pragma: no cover
        raise ImproperlyConfigured("Unable to serialize response content") from e