I’m trying to figure out how to send data to my Lambda function using API Gateway. I want to be able to handle two types of requests:
GET /profile?username=alice
GET /profile/alice
How can I make sure the Lambda function gets the username in both cases? I’ve looked at the API Gateway docs and they mention something about mapping, but I can’t find where to set it up in the console.
I tried adding a query string parameter in the Method Request section, but I don’t see any options to map it to the Lambda function. Same goes for path parameters.
Does anyone know how to set this up correctly? I’m new to AWS and could really use some help getting this working. Thanks!
hey, i’ve been there too. api gateway can be confusing at first. have you tried using the proxy integration? it’s pretty neat cuz it passes everything to lambda automatically. you can grab the username from event[‘queryStringParameters’] or event[‘pathParameters’] in your function. Makes life way easier!
I’ve dealt with this exact issue before, and it can be a bit tricky at first. Here’s what worked for me:
For query parameters, you need to set up the Method Request in API Gateway to expect the parameter. Then, in the Integration Request, you can map it to the event object that Lambda receives.
For path parameters, you’ll need to define them in your resource path (like /{username}) and then set up the mapping in the Integration Request as well.
The key is in the Integration Request section. There’s a ‘Body Mapping Templates’ area where you can create a template that structures the event object. Something like this worked for me:
{
“username”: “$input.params(‘username’)”
}
This will work for both query and path parameters. Just make sure your Lambda function is looking for ‘username’ in the event object.
It took me a while to figure this out, but once you get it set up, it’s pretty powerful. You can even combine multiple parameters this way if needed.
I’ve encountered similar challenges when working with API Gateway and Lambda. One approach that’s worked well for me is utilizing API Gateway’s proxy integration feature. It simplifies the process significantly.
With proxy integration, API Gateway automatically passes all request data to your Lambda function, including query parameters and path variables. You don’t need to set up explicit mappings in the Integration Request.
In your Lambda function, you can then access the data like this:
def lambda_handler(event, context):
username = event['queryStringParameters'].get('username') or event['pathParameters'].get('username')
This handles both your GET /profile?username=alice and GET /profile/alice scenarios seamlessly. It’s a more flexible approach that reduces configuration overhead and allows your Lambda to handle various input formats easily.
Remember to configure your API Gateway resource path as /{proxy+} to enable this functionality. It’s been a game-changer for my API development workflow.