Skip to content

feat(data_classes): add API Gateway Websocket event #6287

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

ericbn
Copy link
Contributor

@ericbn ericbn commented Mar 18, 2025

Issue number: #6161

Summary

Changes

Pydantic models were added for API Gateway WebSocket events here: https://docs.powertools.aws.dev/lambda/python/latest/utilities/parser/#built-in-models

Add the corresponding data model class.

User experience

import requests
from aws_lambda_powertools.utilities.data_classes import (
    APIGatewayWebSocketEvent,
    event_source,
)

session = requests.Session()

@event_source(data_class=APIGatewayWebSocketEvent)
def lambda_handler(event: APIGatewayWebSocketEvent, context):
    params = {
        "connection_id": event.request_context.connection_id,
        "data": event.json_body,
    }
    response = session.post("https://mydomain.com/myapi", data=params)
    if 400 <= response.status_code < 600:
        raise RuntimeError(response.text)
    return {"statusCode": 200}

Checklist

If your change doesn't seem to apply, please leave them unchecked.

Is this a breaking change?

RFC issue number:

Checklist:

  • Migration process documented
  • Implement warnings (if it can live side by side)

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

Pydantic models were added for API Gateway WebSocket events here:
https://docs.powertools.aws.dev/lambda/python/latest/utilities/parser/#built-in-models

Add the corresponding data model class.
@ericbn ericbn requested a review from a team as a code owner March 18, 2025 00:49
@ericbn ericbn requested a review from anafalcao March 18, 2025 00:49
@boring-cyborg boring-cyborg bot added the tests label Mar 18, 2025
@pull-request-size pull-request-size bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Mar 18, 2025
@leandrodamascena leandrodamascena added the event_sources Event Source Data Class utility label Mar 18, 2025
@github-actions github-actions bot added the feature New feature or functionality label Mar 18, 2025
Copy link

codecov bot commented Mar 18, 2025

Codecov Report

Attention: Patch coverage is 97.75281% with 2 lines in your changes missing coverage. Please review.

Project coverage is 96.32%. Comparing base (f5b4e1f) to head (6bf1766).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
...lities/data_classes/api_gateway_websocket_event.py 97.72% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #6287      +/-   ##
===========================================
+ Coverage    96.31%   96.32%   +0.01%     
===========================================
  Files          241      242       +1     
  Lines        11627    11716      +89     
  Branches       863      865       +2     
===========================================
+ Hits         11199    11286      +87     
- Misses         336      337       +1     
- Partials        92       93       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

@leandrodamascena leandrodamascena left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @ericbn! Before I review the PR, can you add tests for lines that codecov is reporting as having no coverage?

Thanks for sending this PR!

@leandrodamascena leandrodamascena removed the request for review from anafalcao March 18, 2025 11:29
@ericbn ericbn requested a review from leandrodamascena March 18, 2025 14:01
@leandrodamascena
Copy link
Contributor

Hey @ericbn! I was running some tests and I'd like to share with you a concern I have.

In the DictWrapper class we expose a raw_event property, which means that the customer can access the raw event of that class or the entire event. Taking the change you made to ALBEvent in request_context as an example, with this change the customer accessing raw_event from request_context will have a different result than it does today. E.g

from aws_lambda_powertools.utilities.data_classes import ALBEvent

data = {

  "requestContext": {
    "elb": {
      "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
    }
  },
  "httpMethod": "GET",
  "path": "/lambda",
  "queryStringParameters": {
    "query": "1234ABCD"
  },
  "headers": {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "accept-encoding": "gzip",
    "accept-language": "en-US,en;q=0.9",
    "connection": "keep-alive",
    "host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com",
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
    "x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
    "x-forwarded-for": "72.12.164.125",
    "x-forwarded-port": "80",
    "x-forwarded-proto": "http",
    "x-imforwards": "20"
  },
  "body": "Test",
  "isBase64Encoded": False
}

my_alb_event = ALBEvent(data)

print(my_alb_event.request_context.raw_event)

Currently:
{'requestContext': {'elb': {'targetGroupArn': 'arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a'}}, 'httpMethod': 'GET', 'path': '/lambda', 'queryStringParameters': {'query': '1234ABCD'}, 'headers': {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'accept-encoding': 'gzip', 'accept-language': 'en-US,en;q=0.9', 'connection': 'keep-alive', 'host': 'lambda-alb-123578498.us-east-2.elb.amazonaws.com', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 'x-amzn-trace-id': 'Root=1-5c536348-3d683b8b04734faae651f476', 'x-forwarded-for': '72.12.164.125', 'x-forwarded-port': '80', 'x-forwarded-proto': 'http', 'x-imforwards': '20'}, 'body': 'Test', 'isBase64Encoded': False}

With this change:
{'elb': {'targetGroupArn': 'arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a'}}

I believe this PR is doing the right thing and this is the correct behavior that the customer can expect, but I'm not sure if we're going to introduce a breaking change to someone. I think we can go ahead with this PR and see if anyone complains about it. What do you think?

@ericbn
Copy link
Contributor Author

ericbn commented Mar 18, 2025

Hey @leandrodamascena. You mean the changes in #6289. I agree there's potential for breaking changes there if users are using the classes in unconventional ways. Also agree we don't need to be too conservative, consider these are edge cases, and see if there's any user complains.

@leandrodamascena
Copy link
Contributor

Hey @leandrodamascena. You mean the changes in #6289. I agree there's potential for breaking changes there if users are using the classes in unconventional ways. Also agree we don't need to be too conservative, consider these are edge cases, and see if there's any user complains.

Oh Deuss! I commented in the wrong PR hahaha! But yes, this is what I'm talking about.

Copy link
Contributor

@leandrodamascena leandrodamascena left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super nice! APPROVED @ericbn!

@leandrodamascena leandrodamascena merged commit a157671 into aws-powertools:develop Mar 18, 2025
12 checks passed
@ericbn ericbn deleted the data_classes_websocket_event branch March 18, 2025 17:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
event_sources Event Source Data Class utility feature New feature or functionality size/L Denotes a PR that changes 100-499 lines, ignoring generated files. tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature request: Event Source Data Classes for API Gateway WebSocket events
2 participants