AWS serverless with Chalice
AWS console provides a fine platform for deploying the serverless codebase regardless of the language it is built with. We are provided with a great platform to edit, test and deploy. But this indeed creates a small pitfall, it slows down the development process.
AWS Chalice allows you to quickly create and deploy applications that use Amazon API Gateway and AWS Lambda.
Prerequisite
- Python 3
- pipenv
- aws cli
- HTTPie (Optional)
Installation
pipenv install chalice
chalice new-project <project_name>
- chalicelib is created manually for having any supporting utilities
- config.json helps us to define the environment and stage details
We can deploy this project even now to AWS (In a case you already have an AWS profile configured) and it would still work seamlessly, all without a peek at AWS console.
AWS Chalice provides us with a mechanism to test the project on our development environment without any hassle.
chalice local --port=<port_number>
This will serve the project on the local development server
Deploying and testing the application on AWS
Below is the code snippet of app.py
- Any error raised would be captured by exception_advice and returned with the respective error code.
- The request would be authorized by Cognito user pool
Now when we deploy the application using chalice deploy, chalice would be creating:
- Lambda function
- API-Gateway and Lambda trigger
- Binding the API call with an authorizer as .
After the successful deployment, we can test the application using HTTPie.
- The first step would involve generating the authorization token using the aws cli. But while using the command we must need to enable SRP based authentication for the app client in AWS Cognito
aws cognito-idp admin-initiate-auth --user-pool-id <user_pool_id> --client-id <client_id> --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=<user>,PASSWORD=<password>
- To test the rest api, I have used HTTPie instead of curl as it provides easy inputs and clear response
http <url> Authorization:"Bearer <token>"
For more details refer HTTPie Documentation
Conclusion
AWS Chalice encapsulates the tedious task of configuring the serverless flow and enables the developer to have firm control over the code.
- It presents an SDK that can be directly linked with the front end code and reduces overhead on the frontend developer.
- It also grants the ability to use AWS SAM instead of managing the deployment ourselves using chalice package
Serverless application is analogous to a functional approach towards programming. They ease the task for maintenance, monitoring and upgrading the platform for our application. AWS Chalice is a minimalistic framework that allows us to invest our efforts in business implementation, rather than focusing on environment configuration.
It is good to know everything, but it is wise to do just few.