Serverless 1: API Gateway, DynamoDB and Lambda Functions
Being around technology for almost a decade, it is incredible to see all the tools available to help us ‘tech-people’ code, think and achieve better results in our professional life. These days, I’ve been deep-diving into a lot of concepts of cloud development and architecture inside AWS and have learned a lot of good stuff to share, right here, right now.
Well, AWS has many features that allow us to create incredible and flexible solutions using the serverless architecture approach (that is, to build and run apps and services without having to manage infrastructure, while your code still runs on servers managed by the cloud provider).
This tutorial series will walk you through the steps to create a simple, yet fast and decoupled, user management API microservice using a NoSQL database, some JSON manipulation and Lambda functions coded in Python to create, read, update and delete records, everything running under the AWS Free Tier usage limit.
First things first!
You can use the AWS SDK and import all the packages to your solution and code from your preferred IDE, but most likely under the hood the SDK will be calling APIs on your behalf, andthat is OK if you want to. But I can point 3 factors that make the serverless approach a better one:
· Security: instead of managing your credentials on config files or hard coding them, you can use IAM roles directly on the AWS Console to grant/deny permissions to the resources you need.
· Reusability: you create one endpoint and can use it in many projects without the need to import libraries or refactor your code.
· Costs: everything you need to use is cloud-based, replicated to different availability zones and pretty much costing less than an on-premises infrastructure.
At the end of the day, this is a new shape of systems architecture right now, and besides, it is fun to discover new ways to do things. So, log into your AWS console and let’s go!
The Scope
You need to manage users for your company, registering them to a database with relevant information and then retrieve, update or delete them later using some parameters.
The DynamoDB Table
First, navigate to the DynamoDB console and select Create Table.
Next, name the table as Users, and make username (string) as the Primary Key. Leave the rest of the default settings and choose Create.
The IAM Role & Policy
Important thing on AWS: least privilege! Your APIs and Lambda functions will need permissions to integrate with each other and to do things on the resources, so let’s create a role to allow our Lambda service to only insert things into DynamoDB.
Go to the IAM Dashboard and choose Roles -> Create Role.
Then, choose AWS Service as the type, Lambda as use case and click Next: Permissions.
Now you need to attach a policy to that role, that will allow only the insert action (PutItem) for DynamoDB. As this is not created by default, click on Create Policy.
In the new screen, use the below information:
· Service: DynamoDB
· Actions: PutItem
· Resources: Specific, then Add ARN, then this info (Region: your-region, Account: your-account-id, Table Name: Users)
Click on Add and then on Review Policy.
Name it DynamoDBPutItemOnly and click Create Policy.
Once done, go back to the Create Role screen, refresh the list clicking in the two-arrows icon, select the DynamoDBPutItemOnly policy and click Next: Tags, and then on Next:Review.
Name the role LambdaDynamoDBPutItemOnly and click on Create role. And that’s it!
The Lambda Function
Navigate to the Lambda section and choose Create Function.
Next, select Author from Scratch and fill in the info below and click on Create Function.
· Function Name: InsertUser
· Runtime: Python 3.8
· Permissions: Use existing role -> LambdaDynamoDBPutItemOnly
In the Function Code section, paste this code.
Lastly, click on Deploy.
The API Gateway Endpoint
Navigate to the API Gateway dashboard and click on Create API.
Choose the REST API section and click Build.
Select New API, name it as Users, for Endpoint Type leave it Regional and click on Create.
You should be directed to the resources section.
Click on Actions and then Create Method. From the small dropdown that will appear, select POST and click on the check mark next to it.
Next, on the Setup page, fill in the form as follows:
· Integration Type: Lambda Function
· Lambda Region: your-region
· Lambda Function: InsertUser
Then click on Save.
You should be prompted to grant API Gateway permissions to invoke your Lambda function. Hit OK.
Time to Test!
In the Method Execution screen, click Test.
In the Test screen, paste the following example in the Request Body section:
{
“user_login”:”raul.tavares”,
“user_pass”:”md5hashedpassword”,
“user_id”:”1",
“user_email”:”admin@raultavares.com”,
“user_fullname”:”Raul Tavares”,
“user_function”:”administrator”
}
And click Test.
API Gateway should return Status 200, the Latency execution time and the Response Body specified in the Lambda function.
You have just inserted your first record to the Users table. Play with it just changing the JSON request information and populate the table as you wish.
Deploying the API
Before you deploy your API for public access, bear in mind that:
· It is really recommended that you establish at least one level of authentication to your API, either through IAM Roles, Cognito User Pools or Lambda Authorizers.
· You can map a custom domain name to your API endpoint to make it more development-friendly.
· It is good-practice to watch for DynamoDB and Lambda logs, as you can reduce costs by adjusting read-write latency and execution running time per your needs.
So, when you’re ready, on the Method Execution screen, click on Actions and Deploy API.
If you do not have a production environment, under the Deployment Stage dropdown, click on New Stage, give it a name, and click Deploy.
Conclusion
And that’s it for the first part!!
You now have a fully functional, working API and can call it from any application like Postman or Swagger using the Invoke URL. This API uses a simple Python function running without installing anything and you can integrate it with any other software, developed in any coding language, only using JSON information back and forth.
See you in the second part soon! Thank you!