Table of contents
If you're new to AWS it can be daunting trying to get started with Lambda functions and APIs - it definitely was for me. In this post I'll take you through how to deploy your first Lambda function and expose it as an API using API Gateway.
Creating your first function
We'll be creating a basic function that works out the percentage change between two numbers.
Navigate to the Lambda service in the AWS console - create a new function, give it any name you like and select Python as the runtime.
Enter the following source code and click Deploy:
import json
def lambda_handler(event, context):
old = int(event['original'])
new = int(event['new'])
result = (((new-old)/old)*100)
return {
'statusCode': 200,
'body': json.dumps(result)
}
You've just deployed your first Lambda function! Now lets add a test event to ensure our function works as expected.
Click on Test and 'Configure test event'. Our keys will be "original" and "new", feel free to try out different values for each. Below I'm using 100 as my original value and 344 as my new value.
Save the event and click Test. If all goes well you should be provided with the execution_results showing the following response:
{
"statusCode": 200,
"body": "244.0"
}
Creating a Rest API
We'll now be creating our API and connecting it to the lambda function.
In the console navigate to API Gateway, Click Create API and select Build under Rest API.
Create a POST method resource and select Lambda function as the integration type. Select the lambda function we just created.
You can test your API method by navigating to Test and inputting the same values as we did when we created our Lambda test event which should provide you with the same response body as before.
It is important to enable CORS which is required to build web applications that access APIs hosted on a different domain or origin.
Next, click Deploy API and create a new stage where your API will be deployed. This will provide you with a URL to invoke.
Testing the API
We'll be using Postman to test our API. Enter the URL making sure to select the POST method. The body values are the same as the values we used to previously test the API. Feel free to try different numbers too.
There you have it! You've now deployed your first Lambda function and exposed it as an API. You can always build on this to create more complex functions and integrate the API with any apps you've created.