Comments (7)
Thank you for the report @pavitra-infocusp - looking into this shortly today.
from powertools-lambda-python.
I might be missing something but I can't reproduce - here's an endpoint I've created to test (code at the bottom): https://pm5mz0wx61.execute-api.eu-west-1.amazonaws.com/Prod/todos
Questions
is this also happening on pre-flight operations OPTIONS
? Could you share how you setup API Gateway?
I've used both cURL and a browser JS test.
curl -s -I -H "Origin: https://docs.powertools.aws.dev" -X GET "https://pm5mz0wx61.execute-api.eu-west-1.amazonaws.com/Prod/todos"
Infra Cors SETUP
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
Complete infra to reproduce lack of CORS headers in #3849
Globals:
Function:
Timeout: 60
MemorySize: 512
Tracing: Active
Runtime: python3.11
Architectures:
- x86_64
Environment:
Variables:
POWERTOOLS_METRICS_NAMESPACE: TodoApp
LOG_LEVEL: INFO
TZ: "Europe/Amsterdam"
Api:
TracingEnabled: true
Cors: # see CORS section: https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/#cors
AllowOrigin: "'*'"
AllowHeaders: "'Content-Type,Authorization,X-Amz-Date'"
MaxAge: "'5'"
Resources:
#####################################################
# API Todos
#
# Flow: API Gateway -> Lambda
# |
# v
# /todos -> Lambda
#
#####################################################
GetTodosFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html
Properties:
Handler: app.lambda_handler
CodeUri: todo_api
Events:
HelloPath:
Type: Api
Properties:
Path: /todos
Method: GET
TodoById:
Type: Api
Properties:
Path: /todos/{todo_id}
Method: GET
CreateTodo:
Type: Api
Properties:
Path: /todos
Method: POST
SwaggerUI:
Type: Api
Properties:
Path: /swagger
Method: GET
SwaggerUICSS:
Type: Api
Properties:
Path: /swagger.css
Method: GET
SwaggerUIJS:
Type: Api
Properties:
Path: /swagger.js
Method: GET
# Powertools env vars: https://awslabs.github.io/aws-lambda-powertools-python/#environment-variables
Environment:
Variables:
POWERTOOLS_SERVICE_NAME: TodoAPI
# POWERTOOLS_DEV: true
Outputs:
GetTodosFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt GetTodosFunction.Arn
TodoEndpoint:
Description: "API Gateway endpoint URL for Prod environment for Todos"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod"
GetTodosAPI:
Description: "API Gateway endpoint URL to fetch todos"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/todos"
Code used
from typing import Annotated, Optional
import requests
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import (
APIGatewayRestResolver,
CORSConfig,
)
from aws_lambda_powertools.event_handler.openapi.params import Query
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.utilities.parser import Field, BaseModel
tracer = Tracer()
logger = Logger()
cors = CORSConfig(max_age=2) # short enough to avoid caching issue
app = APIGatewayRestResolver(enable_validation=True, cors=cors)
app.enable_swagger(path="/swagger")
class Todo(BaseModel):
userId: int
id_: Optional[int] = Field(alias="id", default=None)
title: str
completed: bool
@app.get("/todos")
@tracer.capture_method
def get_todos(
completed: Annotated[str | None, Query(min_length=4)] = None
) -> list[Todo]:
url = "https://jsonplaceholder.typicode.com/todos"
if completed is not None:
url = f"{url}/?completed={completed}"
todo = requests.get(url)
todo.raise_for_status()
return todo.json()
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
def lambda_handler(event: dict, context: LambdaContext) -> dict:
ret = app.resolve(event, context)
# Logging response to be triple sure Event Handler is appending CORS headers
logger.info("Returning response", response=ret)
return ret
from powertools-lambda-python.
I'm glad you found out @pavitra-infocusp -- better safe than sorry :) no worries from our side. Have an awesome day ahead with your new extension!
from powertools-lambda-python.
Thanks for your support!
from powertools-lambda-python.
Thanks for opening your first issue here! We'll come back to you as soon as we can.
In the meantime, check out the #python channel on our Powertools for AWS Lambda Discord: Invite link
from powertools-lambda-python.
Actually, it's not an issue with Powertools at all. It failed on the preflight requests stating CORS issue. Since I'm building a Chrome extension, Chrome doesn't set the Origin
header with the request, unless the URL is specified in the host_permissions
in the manifest. Sorry for the misunderstanding.
from powertools-lambda-python.
⚠️ COMMENT VISIBILITY WARNING⚠️
This issue is now closed. Please be mindful that future comments are hard for our team to see.
If you need more assistance, please either tag a team member or open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.
from powertools-lambda-python.
Related Issues (20)
- Tech debt: add `from __future__ import annotations` in the Event Handler OpenAPI feature HOT 2
- Tech debt: add `from __future__ import annotations` in the Batch Processing feature HOT 2
- Tech debt: add `from __future__ import annotations` in the Event Handler feature HOT 2
- Tech debt: add `from __future__ import annotations` in the Parser models feature HOT 2
- Technical Debt: Enable TCH, UP and FA100 rules in the Ruff linter HOT 6
- Docs: Publish Upgrade Guide for V3 HOT 2
- [Support Powertools for AWS Lambda (Python)]: Pushpay HOT 1
- Bug: Revert changes that impacts v3 HOT 6
- Bug: get_field_info_and_type_annotation doesn't respect tuple return types HOT 8
- Docs: Minor typo for log_level example HOT 5
- Bug: APIGatewayRestResolver with enable_validation=True and custom Response class type hint fails HOT 4
- Feature request: [Bedrock Agent Event Handler] Add (prompt) session attributes and knowledgeBasesConfiguration to the response HOT 2
- Maintenance: update docs to use self-hosted mermaid.js script HOT 1
- Bug: `APIGatewayRestResolver(enable_validation=True)` incompatible with `from __future__ import annotations` HOT 3
- Docs: Addition of docs inventory (`objects.inv`) HOT 4
- Bug: Pydantic deprecated methods are still used HOT 4
- Bug: S3 SQS Event Parsing for LifecycleExpiration:Delete is failed HOT 3
- Docs: Update maintainers table HOT 1
- Bug: response hook is not called when idempotent function returns `None`
- Feature request: Support for large SQS payloads in Event Data Source Classes
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from powertools-lambda-python.