Skip to content

Commit d4f4376

Browse files
committed
feat(event_handler): Allow cookies in response
Changes: - Add cookies field in Response - For http api gateway format 2.0 responses serialize to cookies - For alb and rest api use multiValueHeaders closes aws-powertools#1192
1 parent 8ca082f commit d4f4376

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

aws_lambda_powertools/event_handler/api_gateway.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ def __init__(
140140
content_type: Optional[str],
141141
body: Union[str, bytes, None],
142142
headers: Optional[Dict] = None,
143+
cookies: Optional[List[str]] = None,
143144
):
144145
"""
145146
@@ -154,11 +155,14 @@ def __init__(
154155
Optionally set the response body. Note: bytes body will be automatically base64 encoded
155156
headers: dict
156157
Optionally set specific http headers. Setting "Content-Type" hear would override the `content_type` value.
158+
cookies: Optional[List[str]]
159+
Optionally set cookies
157160
"""
158161
self.status_code = status_code
159162
self.body = body
160163
self.base64_encoded = False
161164
self.headers: Dict = headers or {}
165+
self.cookies = cookies
162166
if content_type:
163167
self.headers.setdefault("Content-Type", content_type)
164168

@@ -220,13 +224,22 @@ def build(self, event: BaseProxyEvent, cors: Optional[CORSConfig] = None) -> Dic
220224
logger.debug("Encoding bytes response with base64")
221225
self.response.base64_encoded = True
222226
self.response.body = base64.b64encode(self.response.body).decode()
223-
return {
227+
228+
response = {
224229
"statusCode": self.response.status_code,
225230
"headers": self.response.headers,
226231
"body": self.response.body,
227232
"isBase64Encoded": self.response.base64_encoded,
228233
}
229234

235+
if self.response.cookies:
236+
if isinstance(event, APIGatewayProxyEventV2):
237+
response["cookies"] = self.response.cookies
238+
else:
239+
response["multiValueHeaders"] = {"Set-Cookie": self.response.cookies}
240+
241+
return response
242+
230243

231244
class BaseRouter(ABC):
232245
current_event: BaseProxyEvent

tests/functional/event_handler/test_api_gateway.py

+32
Original file line numberDiff line numberDiff line change
@@ -1258,3 +1258,35 @@ def handler(event: APIGatewayProxyEventV2, context):
12581258
# THEN
12591259
result = handler(load_event("apiGatewayProxyV2Event.json"), None)
12601260
assert result["statusCode"] == 200
1261+
1262+
1263+
def test_api_gateway_http_cookie():
1264+
# GIVEN
1265+
app = APIGatewayHttpResolver()
1266+
1267+
@app.post("/my/path")
1268+
def my_path() -> Response:
1269+
return Response(200, content_types.TEXT_PLAIN, "Test", cookies=["key=value"])
1270+
1271+
# WHEN
1272+
result = app(load_event("apiGatewayProxyV2Event.json"), {})
1273+
1274+
# THEN
1275+
assert result["headers"]["Content-Type"] == content_types.TEXT_PLAIN
1276+
assert result["cookies"] == ["key=value"]
1277+
1278+
1279+
def test_api_gateway_rest_cookie():
1280+
# GIVEN
1281+
app = APIGatewayRestResolver()
1282+
1283+
@app.get("/my/path")
1284+
def get_lambda() -> Response:
1285+
return Response(200, content_types.TEXT_PLAIN, "Test", cookies=["foo=bar"])
1286+
1287+
# WHEN
1288+
result = app(LOAD_GW_EVENT, {})
1289+
1290+
# THEN
1291+
assert result["headers"]["Content-Type"] == content_types.TEXT_PLAIN
1292+
assert result["multiValueHeaders"]["Set-Cookie"] == ["foo=bar"]

0 commit comments

Comments
 (0)