Lines 7, 12, and 20 are simply logging for our function.
In line 10, you can see we set the âredirect_siteâ variable to the value of the âproxyâ key of the âpathParametersâ parent key of the event that invoked our Lambda (redirect_site = event -> pathParameters -> proxy
). This event is delivered from API Gateway, and is triggered whenever a user visits our API Gateway URL. You can review an example event in my demo repo. The parse.quote()
method is to escape non-URL friendly characters from our user-supplied redirect, in case theyâve somehow slipped into the event.
Down on line 15, we begin to create the response object by creating an empty dictionary. On line 16, we then create a new entry in this dictionary with key âstatusCodeâ and a value of 302 (the HTTP status code we want to deliver to the user). Line 17 just creates an empty body, since weâre going to be redirecting the user anyway.
Line 18 is where the redirect URL is actually set. We create a âheadersâ key in our response dictionary, and populate it with another dictionary with key âLocationâ and value âhttps://www.<redirect_site>.comâ. This is what the userâs browser will redirect to once they get our HTTP 302 response.
Finally, on line 22, we return the response object to API Gateway so it can be delivered to the user.
Terraform
Check out the Terraform files themselves for comments explaining what each resource declaration is and what it does. Let me know if anything is inadequately described or still confusing.
Reviewing Logs in CloudWatch
I mentioned earlier that logging is set up in our Python Lambda function. You can review these logs in the AWS console by going to the CloudWatch dashboard, clicking on âLog Groupsâ under âLogsâ in the left toolbar, and then finding the /aws/lambda/redirect-lambda-example
log group.