99c4e02ecf
Name it instead "topics" so it won't be strange if some topics included "exercises" directory.
2.4 KiB
2.4 KiB
URL Function
Create a basic AWS Lambda function that will be triggered when you enter a URL in the browser
Solution
Define a function
-
Go to Lambda console panel and click on
Create function
-
Give the function a name like
urlFunction
-
Select
Python3
runtime -
Now to handle function's permissions, we can attach IAM role to our function either by setting a role or creating a new role. I selected "Create a new role from AWS policy templates"
-
In "Policy Templates" select "Simple Microservice Permissions"
-
Next, you should see a text editor where you will insert a code similar to the following
Function's code
import json
def lambda_handler(event, context):
firstName = event['name']
return 'Hello ' + firstName
- Click on "Create Function"
Define a test
- Now let's test the function. Click on "Test".
- Select "Create new test event"
- Set the "Event name" to whatever you'd like. For example "TestEvent"
- Provide keys to test
{
"name": 'Spyro'
}
- Click on "Create"
Test the function
- Choose the test event you've create (
TestEvent
) - Click on the
Test
button - You should see something similar to
Execution result: succeeded
- If you'll go to AWS CloudWatch, you should see a related log stream
Define a trigger
We'll define a trigger in order to trigger the function when inserting the URL in the browser
- Go to "API Gateway console" and click on "New API Option"
- Insert the API name, description and click on "Create"
- Click on Action -> Create Resource
- Insert resource name and path (e.g. the path can be /hello) and click on "Create Resource"
- Select the resource we've created and click on "Create Method"
- For "integration type" choose "Lambda Function" and insert the lambda function name we've given to the function we previously created. Make sure to also use the same region
- Confirm settings and any required permissions
- Now click again on the resource and modify "Body Mapping Templates" so the template includes this:
{ "name": "$input.params('name')" }
- Finally save and click on Actions -> Deploy API
Running the function
- In the API Gateway console, in stages menu, select the API we've created and click on the GET option
- You'll see an invoke URL you can click on. You might have to modify it to include the input so it looks similar to this:
.../hello?name=mario
- You should see in your browser
Hello Mario