Build Serverless Application in python within an hour using AWS Chalice

Create and deploy REST API using AWS Lambda and Amazon API gateway

AWS Lambda is a fantastic tool to build serverless applications in AWS. Creating and deploying REST API in python using Flask framework with AWS Lambda and Amazon API gateway can be highly complex. AWS Chalice is a framework for making serverless applications in python. It makes the creation and deployment process very simple. You can create and deploy a simple REST API in a matter of minutes in AWS.

What is Chalice?

Chalice is a framework developed by AWS to write serverless applications in python. It creates and deploy serverless applications using AWS lambda. It provides command line tool to create and deploy the application. It also provides APIs to integrate with Amazon API Gateway, Amazon S3, Amazon SNS, and other AWS services. You can learn more about Chalice on the official website – https://aws.github.io/chalice/.

Let’s build a sample application.

Install Chalice

Check your python version.

$ python3 --version
Python 3.8.3
$ python3 -m venv venv38
$ . venv38/bin/activate

Install Chalice using pip.

$ python3 -m pip install chalice

Verify you have Chalice installed in your system.

$ chalice --version

Configure AWS Credentials

To deploy the serverless application in AWS, it is required to have AWS configured in your system. Use AWS CLI to configure AWS credentials in your system. Verify if you have AWS CLI installed by running the following command.

$ aws --version

If AWS CLI is not installed, follow this document to install AWS CLI. Once AWS CLI is installed, configure AWS credentials by running aws configure command and adding AWS Access Key ID, AWS Secret Access Key and Default region name.

$ aws configure

Create Chalice Application

Create new chalice project named chaliceapp.

$ chalice new-project chaliceapp

A new directory with name “chaliceapp” is created. We can see that multiple files are created in this directory.

.
├── .chalice
│   └── config.json
├── .gitignore
├── app.py
└── requirements.txt

These are the files required to get started with serverless applications on AWS. These are the default files generated by chalice.

Let us look at code of app.py:

from chalice import Chalice

app = Chalice(app_name='chaliceapp')


@app.route('/')
def index():
    return {'hello': 'world'}

The code generated a sample application which returns {‘hello’: ‘world’} when called. Now test this sample in local environment first to validate if chaliceapp is working as expected. As a best practice, it is always recommended to do initial testing in local environment before deploying it in AWS.

Chalice CLI has very helpful utility functions that allows to perform multiple operations. Listing few helpful CLI operations will be used in this example:

  • chalice –help – To list chalice commands and options
  • chalice new-project – To create a new chalice project
  • chalice local – To simulate the application locally
  • chalice deploy – To deploy the application in AWS
  • chalice delete – To delete the resources created in AWS

Simulate sample chalice application locally and validate:

$ chalice local
Serving on http://127.0.0.1:8000

By default, chalice application runs on port 8000. The application endpoints can be tested by running curl request or testing it on Postman tool.

$ curl -X GET http://localhost:8000/
{"hello":"world"}

OR

GET request with url "http://localhost:8000/" in Postman.
{
    "hello": "world"
}

Next, add two new routes as examples in app.py – one GET request and other POST request. Add the routes for creating new user and retrieving user details:

from chalice import Chalice

app = Chalice(app_name='chaliceapp')

@app.route('/')
def index():
    return {'hello': 'world'}

@app.route('/user', methods=['POST'])
def add_new_user():
    # add the logic to insert new user info
    return {
        'statusCode': 200,
        'body': "user info inserted"
    }

@app.route('/user/{user_id}/results', methods=['GET'])
def get_result(user_id):
    responseObject = {}
    # add the logic to retrieve user info
    return {
        'statusCode': 200,
        'body': responseObject
    }

Save and validate the api endpoints in localhost to check if everything is working as expected.

POST request with url "http://localhost:8000/user" in Postman to add the user.
GET request with url "http://localhost:8000/user/{user_id}/results" in Postman to retrieve the user information.

Deploy chalice app in AWS by running deploy command upon confirmation of the desired results in the localhost.

$ chalice deploy
Creating deployment package.
Creating IAM role: chaliceapp-dev
Creating lambda function: chaliceapp-dev
Creating Rest API
Resources deployed:
  - Lambda ARN: arn:aws:lambda:region-name:**********:function:chaliceapp-dev
  - Rest API URL: https://*********.execute-api.region-name.amazonaws.com/api/

Login to AWS console and validate if lambda “chaliceapp-dev” and Rest API are created successfully.

In API the resources and methods are created automatically as per definition of app routes in app.py.

Validate the API in Postman.

POST https://*********.execute-api.region-name.amazonaws.com/api/user

GET https://*********.execute-api.region-name.amazonaws.com/api/user/{user_id}/results

Once testing is completed chalice delete command can be utilized to destroy the resources created for PoC through chalice deploy command.

$ chalice delete
Deleting Rest API: **********
Deleting function: arn:aws:lambda:region-name:**********:function:chaliceapp-dev
Deleting IAM role: chaliceapp-dev

Conclusion

Using chalice serverless application can be created in AWS without any hassle, leveraging lambda runtime environment. Chalice framework helps in deploying the application in AWS without worrying about other dependencies like IAM role. One can keep their focus on business logic and deploy the application in AWS with just one command. For making any changes in the application, update app.py, test in local and redeploy the changes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: