skip to Main Content

I have an API which I created using the AWS API Gateway and it has 2 URL String parameters so my GET call is in the following format

/endpoint?City=NYC&State=NY

I am trying to capture both the City and the State URL String parameters in my Python Lambda function and when I print them out and monitor them in CloudWatch, I see None for both of them. I am not sure what I am missing here

import boto3
import json 

def lambda_handler(event, context):
# Extract city and state from query parameters

query_parameters = event.get('queryStringParameters', {})
city = query_parameters.get('City')  
state = query_parameters.get('State')

# Print city and state values
print('City:', city)
print('State:', state)

if not city or not state:
    return {
        'statusCode': 400,
        'body': 'City and State parameters are required.'
    }

When I execute the following code, the code is going into the error block and I am seeing this as the output

City and State parameters are required.

Is there anything else that I may have missed or what am I doing wrong here?

2

Answers


  1. event has a complex format when passed from API Gateway. You have to check and inspect the documented event format, and get your city and state according to the that format. Specifically, they will be found under pathParameters value in event.

    Login or Signup to reply.
  2. If you are trying to do an API maybe you can consider use powertools

    https://docs.powertools.aws.dev/lambda/python/latest/

    Allow to handle the API Gateway calls with a syntax very similar to Flask or FastAPI.
    https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/

    Something like this should work with powertools

    @app.get("/endpoint")
    def get_endpoint(city: str, state: str )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search