AWS Chalice
Chalice is a microframework for writing serverless applications in Python. It allows developers to quickly create and deploy applications that leverage AWS Lambda and Amazon API Gateway. It features a command-line tool for project management, a decorator-based API for integrating with various AWS services (like S3, SNS, SQS), and automatic IAM policy generation. Currently at version 1.32.0, Chalice is actively maintained by AWS.
Warnings
- gotcha Chalice automatically generates IAM policies for your Lambda functions. While convenient, these auto-generated policies can sometimes be overly permissive. For production environments, it's recommended to review the generated policies (in `.chalice/policy.json`) and manually refine them or disable auto-generation using `manage_iam_role=False` in `config.json` or the `--no-autogen-policy` flag during deployment for fine-grained control.
- gotcha When using `chalice local` for local development and testing, the application runs in your local environment and uses your configured AWS CLI credentials, not the IAM role that would be assumed by the Lambda function in AWS. Ensure your local AWS profile has the necessary permissions to access any AWS services (e.g., DynamoDB, S3) your application interacts with during local testing.
- breaking The `@app.on_s3_event` decorator, used for triggering Lambda functions from S3 events, is incompatible with the `chalice package` command. If your application uses S3 event sources, you cannot use `chalice package` to generate a CloudFormation/SAM template; you must deploy directly using `chalice deploy`.
- gotcha AWS Lambda has specific Python runtime versions it supports. While Chalice aims to support these, always verify that your local Python environment matches a supported AWS Lambda runtime (e.g., Python 3.9 through 3.13 are currently supported) to avoid deployment issues or unexpected behavior.
Install
-
pip install chalice
Imports
- Chalice
from chalice import Chalice
- Response
from chalice import Response
- Rate, Cron
from chalice import Rate, Cron
Quickstart
import os
from chalice import Chalice
# Configure AWS credentials if not already set up via AWS CLI
# os.environ['AWS_ACCESS_KEY_ID'] = os.environ.get('AWS_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY')
# os.environ['AWS_SECRET_ACCESS_KEY'] = os.environ.get('AWS_SECRET_ACCESS_KEY', 'YOUR_SECRET_KEY')
# os.environ['AWS_DEFAULT_REGION'] = os.environ.get('AWS_DEFAULT_REGION', 'us-east-1')
app = Chalice(app_name='my-first-chalice-app')
@app.route('/')
def index():
return {'hello': 'world'}
@app.route('/greet/{name}')
def greet_name(name):
return {'message': f'Hello, {name}!'}
# To deploy:
# 1. Ensure AWS CLI is configured with credentials.
# 2. Run `chalice new-project my-first-chalice-app`
# 3. Replace the generated `app.py` content with the code above.
# 4. Run `chalice deploy` in your project directory.
# To test locally: `chalice local`
# To delete: `chalice delete`