04/22/2021 | News release | Distributed by Public on 04/22/2021 13:20
One of the secret ingredients of practical software engineering is to ensure the solutions are simple and small. That's essentially what the hype around serverless implementations is all about since serverless applications scale automatically with demand and remove the maintenance burden from developers. Of course, since it's all automated, you're going to lose some control and visibility, but the time and effort savings are hard to argue with.
In this article, we're going to use Python and Amazon Web Services (AWS) Lambda to implement a simple REST API by doing the following:
In the quest for simplicity, we'll use AWS CloudFormation to define as much of this process as possible.
Recall that a REST API is simply a way to store and retrieve information with stateless protocols. In this case, our REST API is going to handle information about people's pets. To create it, we'll:
Here's our implementation plan:
Just in case you're new to AWS or their serverless platform known as AWS Lambda, let's run through a quick overview:
You can find all of the code for this project in my GitHub repo. The repo includes an API document and a CloudFormation template that will make it easier to get everything running in your AWS account.
If you don't already have an AWS account, you can sign up for a free tier account here. There shouldn't be any charges to run this example in the free tier, and the CloudFormation approach makes it easy to delete everything when you're done.
Our API will store the following information:
You can view the API in my GitHub repo (see API.json), or you can just view it alongside the interactive documentation for it in the SwaggerHub repo. The API defines two endpoints:
We'll use a CloudFormation (CF) template to set up the infrastructure for this example. You have two choices:
If you want to create your own, you can:
It should only take a minute or two to create all the elements of the new stack. If you'd prefer to provide the infrastructure manually, you'll need to create:
Now that we've created the infrastructure, we'll edit the code in each of the Lambda functions to handle adding and retrieving pet objects from the database table.
On the AWS console, navigate to the Lambda home pagewhere you should see the two functions we created previously.
Let's start by implementing the POST endpoint. If you set up your infrastructure with the CF template, the function is called PetLambda-Set.
We're going to use the boto3library, which provides the AWS SDK for Python. We'll keep the code simple for now, but you could experiment with adding validations and exception handling. Using boto3, we'll connect to the DynamoDB table and insert a new record. If you're following along, copy the code below, and replace the Lambda code with it:
import boto3def lambda_handler(event, context):client = boto3.resource('dynamodb')table = client.Table('Pets')response = table.put_item( Item={ 'id': event['id'], 'name': event['name'], 'breed': event['breed'], 'gender': event['gender'], 'owner': event['owner'], 'birthday': event['birthday']}) return { 'statusCode': response['ResponseMetadata']['HTTPStatusCode'], 'body': 'Record ' + event['id'] + ' added' }
If you want to test the Lambda function, Select the Test tab, create a new test from the hello-worldtemplate, and use the example dataset shown below:
{'id': 'd290f1ee-6c54-4b01-90e6-d701748f0851','name': 'Hansie','breed': 'Dachshund','gender': 'Male','owner': 'Mike','birthday': '2012-05-15'}
The response should look similar to that shown below:
{ 'statusCode': 200, 'body': 'Record d290f1ee-6c54-4b01-90e6-d701748f0851 added'}
Now let's follow the same steps to update the PetLambda-Get function. The code below:
import boto3def lambda_handler(event, context):client = boto3.resource('dynamodb')table = client.Table('Pets')response = table.get_item( Key={ 'id': event['id']}) if 'Item' in response: return response['Item'] else: return { 'statusCode': '404', 'body': 'Not found' }
You can test this Lambda by sending in the following test data:
{'id': 'd290f1ee-6c54-4b01-90e6-d701748f0851'}
With our two Lambda functions created and connected to the database, it's time to add an API Gateway to expose the API functionality. On the AWS Console, navigate to the API Gateway home pageand select the Build option to create a REST API:
At this point, you can:
Let's do the following:
Now we'll connect the GET and POST endpoints to each of our Lambda functions:
Configuring the GETendpoint is similar, although we'll need to configure a way to map the query stringto the Lambda parameters:
In the Generate Template box, paste the following:
{ 'id': '$input.params('id')'}
This configuration will map the query string parameter to an input parameter for the Lambda. Click Save when you're done.
Okay, time to deploy our API and make sure everything is set up and working properly. From the main screen for your API, click on Actions, and choose Deploy API.
Choose [New Stage]from the Deployment stage dropdown, and then enter a name (such as Test) and a description. Click Deploy when you're done.
AWS will now deploy your API and make it available to be invoked on the Web. You'll find a custom URL at the top of the page, and options below to enable throttling and various security options.
Copy the URL to your browser and add /pet?id=d290f1ee-6c54-4b01-90e6-d701748f0851 to the end of it. If you followed this example and tested your Lambda with the data set I provided, you should see the JSON object returned in your browser.
You can also use PostMan, Insomnia, or other API tools to post different datasets to the endpoint. You'll need to add /petto the end of the URLprovided for you.
Remember that AWS charges you for everything that's running on your account, so when you're done with the example in this post, don't forget to clean up the API, Lambdas, and other infrastructure. The simplest way is:
If you'd like to learn more about Amazon's API Gateway, the Developer Guideis an excellent place to start. As you can see from the example above, if you have an API document, it doesn't take much to provision Lambda functions and configure them behind an API gateway.
If you want to explore more of what you can do with Python and AWS Lamda, try our pre-built Cloud Computing Python Environment for Windows, Mac and Linux.
It bundles up Python 3.8.2 and boto3 so you can just install it and start driving your AWS implementation using Python right away!
Mike Mackrory is a Global citizen who has settled down in the Pacific Northwest-for now. By day he works as a Senior Engineer on a Quality Engineering team and by night he writes, consults on several web based projects and runs a marginally successful eBay sticker business. When he's not tapping on the keys, he can be found hiking, fishing and exploring both the urban and the rural landscape with his kids. Always happy to help out another developer, he has a definite preference for helping those who bring gifts of gourmet donuts, craft beer and/or Single-malt Scotch.