### Setup Virtual Environment and Install Dependencies
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Create a Python virtual environment and install project dependencies using pip.
```bash
$ python3 -m /tmp/venv37
$ . /tmp/venv37/bin/activate
$ pip install ./requirements-dev.txt
$ pip install ./requirements.txt
```
--------------------------------
### Example URL Parameter Mapping
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/views.md
Illustrates how URL parameters are mapped to view function arguments with example GET requests.
```default
GET /cities/seattle --> index('seattle')
GET /cities/portland --> index('portland')
```
--------------------------------
### Install Chalice and Create Project
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/customdomain.md
Steps to install Chalice, create a virtual environment, and initialize a new Chalice project.
```bash
python3 --version
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install chalice
chalice new-project customdomain
cd customdomain
```
--------------------------------
### Install Boto3
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/events.md
Install the boto3 library to interact with AWS services like SNS.
```bash
$ pip install boto3
```
--------------------------------
### Install Chalice and Create Project
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wschat.md
Installs Chalice, creates a new project, and navigates into the project directory.
```bash
pip install -U chalice
chalice new-project chalice-chat-example
cd chalice-chat-example
```
--------------------------------
### Install Chalice and Create Project
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/basicrestapi.md
Steps to set up Chalice and create a new project. Ensure Python 3.10.20 or later is installed.
```bash
python3 --version
Python 3.10.20
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install chalice
chalice new-project helloworld
cd helloworld
```
--------------------------------
### Install Chalice and Create Project
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wsecho.md
Installs Chalice, creates a new project, and navigates into the project directory.
```bash
pip install -U chalice
chalice new-project echo-server
cd echo-server
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
Install the Python dependencies required for the project by running `pip install` with the top-level `requirements.txt` file.
```bash
python3 -m pip install -r requirements.txt
```
--------------------------------
### Install Project Requirements
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wsecho.md
Installs the project's dependencies, including boto3, locally.
```bash
pip install -r requirements.txt
```
--------------------------------
### JavaScript SDK Example for API Gateway
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/sdks.md
This HTML file demonstrates how to use the JavaScript SDK to interact with API Gateway endpoints defined by Chalice routes. It includes setup for necessary libraries and examples for GET and PUT requests.
```html
SDK Test
result of rootGet()
result of fooGet()
result of helloNameGet({name: 'jimmy'})
result of usersUserIdPut({user_id: '123'})
```
--------------------------------
### Set up Python Virtual Environment and Install Chalice
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
Create a Python virtual environment, activate it, and install the Chalice framework. Ensure you are using Python 3.6 or greater.
```bash
$ python3 -m venv demo
$ . demo/bin/activate
$ python3 -m pip install chalice
```
--------------------------------
### Install HTTPie
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
Install the HTTPie command-line HTTP client, which is used for interacting with the application's API.
```bash
$ pip install httpie
```
--------------------------------
### Install Chalice and Create New Project
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/events.md
Basic commands to set up a new Chalice project and its virtual environment.
```bash
python3 --version
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install chalice
chalice new-project chalice-sns-demo
cd chalice-sns-demo
```
--------------------------------
### Install WebSocket Client
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wsecho.md
Installs the websocket-client package, which provides the wsdump.py tool for testing WebSocket connections.
```bash
pip install websocket-client
```
--------------------------------
### Install Chalice and AWS CLI, Create New Project
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/cfn.md
Installs necessary packages and creates a new Chalice project. Ensure you activate the virtual environment before proceeding.
```bash
$ virtualenv /tmp/venv
$ . /tmp/venv/bin/activate
$ pip install chalice awscli
$ chalice new-project test-cfn-deploy
$ cd test-cfn-deploy
```
--------------------------------
### Testing Deployed API with httpie
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/basicrestapi.md
Examples of making GET requests to the deployed API endpoint using the httpie tool.
```bash
http https://endpoint/api/cities/seattle
HTTP/1.1 200 OK
{
"state": "WA"
}
http https://endpoint/api/cities/portland
HTTP/1.1 200 OK
{
"state": "OR"
}
```
--------------------------------
### Verify Chalice Installation
Source: https://github.com/aws/chalice/blob/master/docs/source/quickstart.md
Check if Chalice is installed correctly by running the --help command.
```bash
chalice --help
```
--------------------------------
### Install Pytest
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/testing.md
Install the pytest testing framework to run your Chalice application tests.
```bash
$ pip install pytest
$ py.test tests/test_app.py
```
--------------------------------
### Install Chalice
Source: https://github.com/aws/chalice/blob/master/docs/source/quickstart.md
Install Chalice using pip within a Python virtual environment.
```bash
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install chalice
```
--------------------------------
### Install Chalice and AWS CLI
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/tf.md
Installs necessary packages and creates a new Chalice project. Ensure you are in a virtual environment.
```bash
$ virtualenv /tmp/venv
$ . /tmp/venv/bin/activate
$ pip install chalice awscli
$ chalice new-project test-tf-deploy
$ cd test-tf-deploy
```
--------------------------------
### Configuration Precedence Example
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/configfile.md
Demonstrates configuration precedence for 'api_gateway_stage'. Stage-specific settings override top-level defaults.
```json
{
"version": "2.0",
"app_name": "app",
"api_gateway_stage": "api",
"stages": {
"dev": {
},
"beta": {
},
"prod": {
"api_gateway_stage": "prod",
"manage_iam_role": false,
"iam_role_arn": "arn:aws:iam::...:role/prod-role"
}
}
}
```
--------------------------------
### Requirements File Example
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/packaging.md
Shows a sample requirements.txt file listing third-party Python packages for the Chalice application.
```text
$ cat requirements.txt
sortedcontainers==1.5.4
```
--------------------------------
### Handle GET and PUT requests with request metadata
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/basicrestapi.md
Use `app.current_request` to access request details like method and JSON body. This example implements a key-value store where PUT creates/updates an object and GET retrieves it. Handles `NotFoundError` for non-existent keys.
```python
from chalice import NotFoundError
OBJECTS = {
}
@app.route('/objects/{key}', methods=['GET', 'PUT'])
def myobject(key):
request = app.current_request
if request.method == 'PUT':
OBJECTS[key] = request.json_body
elif request.method == 'GET':
try:
return {key: OBJECTS[key]}
except KeyError:
raise NotFoundError(key)
```
--------------------------------
### Install Dependencies and Chalice
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
Install the necessary Python packages, including Chalice, using pip and the requirements.txt file.
```bash
$ pip install -r requirements.txt
$ pip install chalice
```
--------------------------------
### Install AWS CLI
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wschat.md
Installs the AWS Command Line Interface for deploying CloudFormation templates.
```bash
pip install -U awscli
```
--------------------------------
### Clone Repository and Setup Directory
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
Clone the Chalice GitHub repository and copy the sample code to a new directory for local development.
```bash
$ git clone git://github.com/aws/chalice
$ mkdir /tmp/demo
$ cp -r chalice/docs/source/samples/media-query/code/ /tmp/demo/media-query
$ cd /tmp/demo/media-query/
```
--------------------------------
### Chalice Application Example
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/sdks.md
This is an example of a Chalice application with several routes defined using the `@app.route()` decorator. These routes will be used to generate the API Gateway SDK.
```python
from chalice import Chalice
app = Chalice(app_name='sdktest')
@app.route('/', cors=True)
def index():
return {'hello': 'world'}
@app.route('/foo', cors=True)
def foo():
return {'foo': True}
@app.route('/hello/{name}', cors=True)
def hello_name(name):
return {'hello': name}
@app.route('/users/{user_id}', methods=['PUT'], cors=True)
def update_user(user_id):
return {"msg": "fake updated user", "userId": user_id}
```
--------------------------------
### Install Chalice with Development Dependencies
Source: https://github.com/aws/chalice/blob/master/CONTRIBUTING.rst
Installs Chalice in editable mode and includes development requirements for bug fixing and feature additions.
```bash
$ pip install -e ".[event-file-poller]"
$ pip install -r requirements-dev.txt
```
--------------------------------
### Environment Variables Configuration
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/configfile.md
This example illustrates how to set environment variables at both the top level (shared across stages) and per stage.
```json
{
"version": "2.0",
"app_name": "app",
"environment_variables": {
"SHARED_CONFIG": "foo",
"OTHER_CONFIG": "from-top"
},
"stages": {
"dev": {
"environment_variables": {
"TABLE_NAME": "dev-table",
"OTHER_CONFIG": "dev-value"
}
},
"prod": {
"environment_variables": {
"TABLE_NAME": "prod-table",
"OTHER_CONFIG": "prod-value"
}
}
}
}
```
--------------------------------
### Verify Chalice Installation
Source: https://github.com/aws/chalice/blob/master/README.rst
Check if Chalice is installed correctly by running the 'chalice --help' command. This will display the available Chalice commands and options.
```bash
chalice --help
Usage: chalice [OPTIONS] COMMAND [ARGS]...
```
--------------------------------
### Install AWS CDK Globally
Source: https://github.com/aws/chalice/blob/master/chalice/templates/6001-cdk-ddb/README.rst
Install the AWS CDK command-line interface globally using npm. This is a prerequisite for deploying the application with the CDK.
```bash
$ npm install -g aws-cdk
```
--------------------------------
### Initialize Terraform
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/tf.md
Initializes the Terraform working directory and installs the AWS provider. This command should be run from the directory containing the `chalice.tf.json` file.
```bash
$ cd /tmp/packaged-app
$ terraform init
```
--------------------------------
### Example of Query String Usage
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/routing.md
Demonstrates the output of a route with and without a query string parameter. The 'include-greeting' parameter conditionally adds a greeting to the response.
```shell
$ http https://endpoint/api/users/bob
{
"name": "bob"
}
$ http https://endpoint/api/users/bob?include-greeting=true
{
"greeting": "Hello, bob",
"name": "bob"
}
```
--------------------------------
### Verify Chalice Installation
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
Confirm that Chalice has been installed correctly by checking its version. This also displays the Python version and operating system.
```bash
$ chalice --version
```
--------------------------------
### Install Project Requirements
Source: https://github.com/aws/chalice/blob/master/chalice/templates/6001-cdk-ddb/README.rst
Install the Python dependencies for the Chalice application using pip. Ensure you are in the root directory of the Chalice application.
```bash
$ pip install -r requirements.txt
```
--------------------------------
### Example of reading a vendor file without automatic layers
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/packaging.md
Without automatic Lambda layers, files in the `vendor/` directory are available in the application's current working directory. This example shows how to directly open a file from the vendor directory.
```python
@app.lambda_function()
def handler(event, context):
with open('myimage.png') as f:
do_something(f)
```
--------------------------------
### Example Usage of Request Object
Source: https://github.com/aws/chalice/blob/master/docs/source/api.md
An example demonstrating how to use the `Request` object within a Chalice route to handle different HTTP methods and access request details.
```APIDOC
## Example Usage of Request Object
This example shows how to access and use the `Request` object within a Chalice route handler.
```python
from chalice import Chalice
app = Chalice(app_name='my-app')
@app.route('/objects/{key}', methods=['GET', 'PUT'])
def myobject(key):
request = app.current_request # type: Request
if request.method == 'PUT':
# Handle PUT request, e.g., access request.json_body or request.raw_body
return {'message': 'PUT request received'}
elif request.method == 'GET':
# Handle GET request, e.g., access request.query_params or request.headers
return {'message': 'GET request received', 'key': key}
```
### Accessing Query Parameters Example:
```python
request = app.current_request
# Raises an exception if key doesn't exist.
single_param = request.query_params['single']
# Returns None if key doesn't exist.
another_param = request.query_params.get('another_param')
# Returns a list of all parameters named 'multi_param'.
multi_param_list = request.query_params.getlist('multi_param')
```
```
--------------------------------
### Chalice Configuration for Environment Variables
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
Example Chalice configuration showing environment variables set for the 'dev' stage, including resource names and ARNs.
```json
{
"version": "2.0",
"app_name": "media-query",
"stages": {
"dev": {
"api_gateway_stage": "api",
"autogen_policy": false,
"environment_variables": {
"MEDIA_TABLE_NAME": "media-query-MediaTable-10QEPR0O8DOT4",
"MEDIA_BUCKET_NAME": "media-query-mediabucket-fb8oddjbslv1",
"VIDEO_TOPIC_NAME": "media-query-VideoTopic-KU38EEHIIUV1",
"VIDEO_ROLE_ARN": "arn:aws:iam::123456789123:role/media-query-VideoRole-1GKK0CA30VCAD",
"VIDEO_TOPIC_ARN": "arn:aws:sns:us-west-2:123456789123:media-query-VideoTopic-KU38EEHIIUV1"
}
}
}
}
```
--------------------------------
### Basic Chalice Middleware Example
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/middleware.md
This example demonstrates a basic middleware function that logs messages before and after the main Lambda function is invoked. It is registered to run for all event types.
```python
from chalice import Chalice
app = Chalice(app_name='demo-middleware')
@app.middleware('all')
def my_middleware(event, get_response):
app.log.info("Before calling my main Lambda function.")
response = get_response(event)
app.log.info("After calling my main Lambda function.")
return response
@app.route('/')
def index():
return {'hello': 'world'}
@app.on_sns_message('mytopic')
def sns_handler(event):
pass
```
--------------------------------
### Download Package Source
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/packaging.md
Use `pip download` to get the source distribution (tar.gz) and any available wheel files for a package and its dependencies.
```bash
$ pip download cryptography==1.9
```
--------------------------------
### Chalice App Setup for WebSockets
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wschat.md
Initializes the Chalice app, sets up the WebSocket API session, enables experimental WebSocket features, and configures storage, sender, and handler instances.
```python
from boto3.session import Session
from chalice import Chalice
from chalicelib import Storage
from chalicelib import Sender
from chalicelib import Handler
app = Chalice(app_name="chalice-chat-example")
app.websocket_api.session = Session()
app.experimental_feature_flags.update([
'WEBSOCKETS'
])
STORAGE = Storage.from_env()
SENDER = Sender(app, STORAGE)
HANDLER = Handler(STORAGE, SENDER)
```
--------------------------------
### Define API Routes with Blueprint
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/blueprints.md
Create a Blueprint object to group related API routes. This example defines routes for the root path and '/foo'.
```python
from chalice import Blueprint
myapi = Blueprint(__name__)
@myapi.route('/')
def index():
return {'hello': 'world'}
@myapi.route('/foo')
def index():
return {'foo': 'bar'}
```
--------------------------------
### Initialize Chalice CDK Construct
Source: https://github.com/aws/chalice/blob/master/docs/source/api.md
Instantiate the Chalice CDK construct within a CDK scope. This example shows how to configure environment variables for the Chalice application.
```python
chalice = Chalice(
self, 'ChaliceApp', source_dir='../runtime',
stage_config={
'environment_variables': {
'MY_ENV_VAR': 'FOO'
}
}
)
```
--------------------------------
### Test Deployed Application
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/tf.md
Uses the outputted EndpointURL from Terraform to test the deployed Chalice application. This example uses `httpie` to make a GET request.
```bash
$ http "$(terraform output EndpointURL)"
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 18
Content-Type: application/json
...
{
"hello": "world"
}
```
--------------------------------
### List All Media with Chalice
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
This snippet shows how to list all available media files using a Chalice application. It assumes a setup where media files are stored and accessible via an API endpoint.
```python
from chalice import Chalice
app = Chalice(app_name='media-query')
@app.route('/media', methods=['GET'])
def list_media():
return [
{
"labels": [
"Video",
"Sample"
],
"name": "sample.mp4",
"type": "video"
}
]
```
--------------------------------
### Verify AWS CDK Installation
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
Check the installed version of the AWS CDK to confirm the installation was successful. This command should output the version number.
```bash
$ cdk --version
```
--------------------------------
### JavaScript SDK Usage Examples
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/sdks.md
These JavaScript snippets demonstrate how to use the generated SDK methods to interact with the Chalice application's routes. Each method corresponds to a specific `@app.route()` definition.
```javascript
var apigClient = apigClientFactory.newClient();
// @app.route('/')
apigClient.rootGet().then(result => {
document.getElementById('root-get').innerHTML = JSON.stringify(result.data);
});
// @app.route('/foo')
apigClient.fooGet().then(result => {
document.getElementById('foo-get').innerHTML = JSON.stringify(result.data);
});
// @app.route('/hello/{name}')
apigClient.helloNameGet({name: 'jimmy'}).then(result => {
document.getElementById('helloname-get').innerHTML = JSON.stringify(result.data);
});
// @app.route('/users/{user_id}', methods=['PUT'])
apigClient.usersUserIdPut({user_id: '123'}, 'body content').then(result => {
document.getElementById('users-userid-put').innerHTML = JSON.stringify(result.data);
});
```
--------------------------------
### Example usage of the key-value store API
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/basicrestapi.md
Demonstrates the workflow of interacting with the key-value store API. First, it shows retrieving a non-existent key results in a 404. Then, it shows creating a key with a PUT request and its JSON body. Finally, it retrieves the created key-value pair.
```shell
# First, trying to retrieve the key will return a 404.
$ http GET https://endpoint/api/objects/mykey
HTTP/1.1 404 Not Found
{
"Code": "NotFoundError",
"Message": "mykey"
}
# Next, we'll create that key by sending a PUT request.
$ echo '{"foo": "bar"}' | http PUT https://endpoint/api/objects/mykey
HTTP/1.1 200 OK
null
# And now we no longer get a 404, we instead get the value we previously
# put.
$ http GET https://endpoint/api/objects/mykey
HTTP/1.1 200 OK
{
"mykey": {
"foo": "bar"
}
}
```
--------------------------------
### Create Chalice Project and Blueprint Files
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/blueprints.md
Initializes a new Chalice project and creates necessary directories and files for organizing blueprints.
```bash
$ chalice new-project blueprint-demo
$ cd blueprint-demo
$ mkdir chalicelib
$ touch chalicelib/__init__.py
$ touch chalicelib/blueprints.py
```
--------------------------------
### Navigate and Inspect Project Structure
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
Change directory into the newly created project and use the `tree` command to view the generated project structure. Note the `infrastructure` and `runtime` directories.
```bash
$ cd cdkdemo
$ tree
.
├── README.rst
├── infrastructure # CDK Application
│| ├── app.py
│| ├── cdk.json
│| ├── requirements.txt
│| └── stacks
│| ├── __init__.py
│| └── chaliceapp.py
├── requirements.txt
└── runtime # Chalice Application
├── app.py
└── requirements.txt
```
--------------------------------
### Create a New Chalice Project
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/stages.md
Initializes a new Chalice project and deploys it to the default 'dev' stage.
```bash
$ chalice new-project myapp
$ cd myapp
$ chalice deploy
...
https://mmnkdi.execute-api.us-west-2.amazonaws.com/api/
```
--------------------------------
### Create Test Files for Chalice App
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/testing.md
Create a `tests/` directory and initialize `__init__.py` and `test_app.py` files for testing the Chalice application.
```bash
$ mkdir tests
$ touch tests/{__init__.py,test_app.py}
```
--------------------------------
### Upload Sample Media Files
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
Upload sample JPG and MP4 files to the S3 bucket using the AWS CLI.
```bash
$ aws s3 cp assets/sample.jpg s3://media-query-mediabucket-xtrhd3c4b59/sample.jpg
$ aws s3 cp assets/sample.mp4 s3://media-query-mediabucket-xtrhd3c4b59/sample.mp4
```
--------------------------------
### Bootstrap CDK Environment
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
If this is your first time using AWS CDK, bootstrap your AWS account. This command deploys a CloudFormation stack with necessary resources for CDK operations. Run this from the `infrastructure` directory.
```bash
$ cd infrastructure
$ cdk bootstrap
Packaging Chalice app for cdkdemo
Creating deployment package.
The stack cdkdemo already includes a CDKMetadata resource
⏳ Bootstrapping environment aws://12345/us-west-2...
CDKToolkit: creating CloudFormation changeset...
[██████████████████████████████████████████████████████████] (3/3)
✅ Environment aws://12345/us-west-2 bootstrapped.
```
--------------------------------
### Configure IAM Policies Across Stages
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/configfile.md
This example shows how to configure IAM policies for different stages. 'dev' uses autogenerated policies, 'beta' uses a specified policy file, and 'prod' uses a pre-existing IAM role ARN.
```json
{
"version": "2.0",
"app_name": "app",
"stages": {
"dev": {
"autogen_policy": true,
"api_gateway_stage": "dev"
},
"beta": {
"autogen_policy": false,
"iam_policy_file": "beta-app-policy.json"
},
"prod": {
"manage_iam_role": false,
"iam_role_arn": "arn:aws:iam::...:role/prod-role"
}
}
}
```
--------------------------------
### Sample app.py
Source: https://github.com/aws/chalice/blob/master/docs/source/quickstart.md
The default app.py file created by 'chalice new-project' defines a single route '/' that returns a JSON response.
```python
from chalice import Chalice
app = Chalice(app_name='helloworld')
@app.route('/')
def index():
return {'hello': 'world'}
```
--------------------------------
### Get Todo by UID (GET /todos/{uid})
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Retrieves a specific todo item by its unique identifier (UID) for the authenticated user. Requires JWT authentication.
```python
@app.route('/todos/{uid}', methods=['GET'], authorizer=jwt_auth)
def get_todo(uid):
username = get_authorized_username(app.current_request)
return get_app_db().get_item(uid, username=username)
```
--------------------------------
### WebSocket Client Interaction Example
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wschat.md
Demonstrates connecting to the deployed WebSocket API using `wsdump.py` and interacting with the chat application. This includes sending messages, joining rooms, listing users/rooms, and quitting.
```bash
$ wsdump.py wss://{id}.execute-api.{region}.amazonaws.com/api/
Press Ctrl+C to quit
> John
< Using nickname: John
Type /help for list of commands.
> /help
< Commands available:
/help
Display this message.
/join {chat_room_name}
Join a chatroom named {chat_room_name}.
/nick {nickname}
Change your name to {nickname}. If no {nickname}
is provided then your current name will be printed
/room
Print out the name of the room you are currently
in.
/ls
If you are in a room, list all users also in the
room. Otherwise, list all rooms.
/quit
Leave current room.
If you are in a room, raw text messages that do not start
with a / will be sent to everyone else in the room.
> /join chalice
< Joined chat room "chalice"
< Jenny joined room.
> Hi
< John: Hi
< Jenny is now known as JennyJones.
> /quit
< Left chat room "chalice"
> /ls
< chalice
> Ctrl-D
```
--------------------------------
### Create User with users.py
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Use this script to create a new user account for the application. It prompts for a username and password.
```bash
$ python users.py --create-user
Username: myusername
Password:
```
--------------------------------
### Configure AWS Credentials
Source: https://github.com/aws/chalice/blob/master/docs/source/quickstart.md
Set up AWS credentials by creating or editing the ~/.aws/config file. Ensure you replace placeholders with your actual keys and region.
```bash
mkdir ~/.aws
cat >> ~/.aws/config
[default]
aws_access_key_id=YOUR_ACCESS_KEY_HERE
aws_secret_access_key=YOUR_SECRET_ACCESS_KEY
region=YOUR_REGION (such as us-west-2, us-west-1, etc)
```
--------------------------------
### Test a Chalice REST API GET Route
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/testing.md
Uses the Chalice test client to send a GET request to the root route and asserts that the JSON response body is as expected.
```python
from chalice.test import Client
from app import app
def test_index():
with Client(app) as client:
response = client.http.get('/')
assert response.json_body == {'hello': 'world'}
```
--------------------------------
### Install Chalice with CDK v2 Support
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
Install the optional Chalice package that includes support for AWS CDK version 2. This is required for integrating Chalice with the latest CDK features.
```bash
$ python3 -m pip install "chalice[cdkv2]"
```
--------------------------------
### Make HTTP Request with Test Client
Source: https://github.com/aws/chalice/blob/master/docs/source/api.md
Use the `http` attribute of the `Client` to simulate HTTP requests to your Chalice REST API. The `get` method makes a GET request to the specified path.
```python
with Client(app) as client:
response = client.http.get("/my-route")
```
--------------------------------
### Create Application Resources
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Run the provided script to create necessary AWS resources like DynamoDB tables and SSM parameters for JWT authentication.
```bash
$ python create-resources.py
```
--------------------------------
### Get Todo
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Retrieves a specific todo item by its unique identifier (uid) for the authenticated user.
```APIDOC
## GET /todos/{uid}
### Description
Retrieves a specific todo item by its unique identifier (uid) for the authenticated user.
### Method
GET
### Endpoint
/todos/{uid}
### Parameters
#### Path Parameters
- **uid** (string) - Required - The unique identifier of the todo item to retrieve.
#### Query Parameters
- None
#### Request Body
- None
### Response
#### Success Response (200)
- The requested todo item, including its 'uid', 'description', 'state', and 'metadata'.
#### Response Example
{
"example": "{\"uid\": \"some-uid\", \"description\": \"Buy groceries\", \"state\": \"pending\", \"metadata\": {}}"
}
```
--------------------------------
### Get Chalice Stage URLs
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/stages.md
Retrieves the API Gateway URLs for different deployed stages.
```bash
$ chalice url --stage dev
https://mmnkdi.execute-api.us-west-2.amazonaws.com/api/
$ chalice url --stage prod
https://wk9fhx.execute-api.us-west-2.amazonaws.com/api/
```
--------------------------------
### List Todos After Creation
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Retrieve the list of todos again after creating a new one to verify the addition. Requires the Authorization header.
```bash
$ http https://abcd.execute-api.us-west-2.amazonaws.com/api/todos/ 'Authorization: my.jwt.token'
HTTP/1.1 200 OK
Content-Length: 136
Content-Type: application/json
[
{
"description": "My first Todo",
"metadata": {},
"state": "unstarted",
"uid": "e25643f7-0b18-47d2-b124-4e6713ab527c",
"username": "myusername"
}
]
```
--------------------------------
### List Todos (GET /todos)
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Retrieves a list of todo items for the authenticated user. Requires JWT authentication.
```python
@app.route('/todos', methods=['GET'], authorizer=jwt_auth)
def list_todos():
username = get_authorized_username(app.current_request)
return get_app_db().list_items(username=username)
```
--------------------------------
### Custom Authorizer with Chalice 0.8.1
Source: https://github.com/aws/chalice/blob/master/docs/source/upgrading.md
This example shows how to use a `CustomAuthorizer` with the `authorizer` argument in `@app.route` for custom authentication logic.
```python
from chalice import Chalice, CustomAuthorizer
app = Chalice(app_name='my-app')
authorizer = CustomAuthorizer(
'MyCustomAuth', header='Authorization',
authorizer_uri=('arn:aws:apigateway:region:lambda:path/2015-03-01'
'/functions/arn:aws:lambda:region:account-id:'
'function:FunctionName/invocations'))
@app.route('/custom-auth', methods=['GET'], authorizer=authorizer)
def authenticated():
return {"secure": True}
```
--------------------------------
### Create New Chalice Project
Source: https://github.com/aws/chalice/blob/master/docs/source/quickstart.md
Use the 'chalice new-project' command to scaffold a new Chalice application. This creates a project directory with essential files.
```bash
chalice new-project helloworld
cd helloworld
ls -la
```
--------------------------------
### Testing Chalice API with httpie
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/cdk.md
Use httpie to send POST and GET requests to your Chalice API endpoint for testing.
```bash
python3 -m pip install httpie
http POST https://abcd.execute-api.us-west-2.amazonaws.com/api/users/ username=jamesls name=James
HTTP/1.1 200 OK
...
{}
http https://abcd.execute-api.us-west-2.amazonaws.com/api/users/jamesls
HTTP/1.1 200 OK
Content-Type: application/json
...
{
"name": "James",
"username": "jamesls"
}
```
--------------------------------
### Get Media Bucket Name
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
Use the AWS CLI to retrieve the name of the S3 bucket used for storing media files.
```bash
$ aws cloudformation describe-stacks --stack-name media-query \
--query "Stacks[0].Outputs[?OutputKey=='MediaBucketName'].OutputValue" \
--output text
media-query-mediabucket-xtrhd3c4b59
```
--------------------------------
### Run All Tests with Make
Source: https://github.com/aws/chalice/blob/master/CONTRIBUTING.rst
Convenience command to run both unit and functional tests using the Makefile.
```bash
make test
```
--------------------------------
### Handle Websocket Events (Connect, Message, Disconnect)
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/websockets.md
This example demonstrates handling new connections, incoming messages, and disconnections using specific decorators. It prints connection IDs and message bodies to CloudWatch Logs.
```python
from boto3.session import Session
from chalice import Chalice
app = Chalice(app_name='test-websockets')
app.experimental_feature_flags.update([
'WEBSOCKETS',
])
app.websocket_api.session = Session()
@app.on_ws_connect()
def connect(event):
print('New connection: %s' % event.connection_id)
@app.on_ws_message()
def message(event):
print('%s: %s' % (event.connection_id, event.body))
@app.on_ws_disconnect()
def disconnect(event):
print('%s disconnected' % event.connection_id)
```
--------------------------------
### Chalice App Definition
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/configfile.md
A basic Chalice application with two lambda functions, 'foo' and 'bar'. This serves as the basis for the subsequent configuration example.
```python
from chalice import Chalice
app = Chalice(app_name='demo')
@app.lambda_function()
def foo(event, context):
pass
@app.lambda_function()
def bar(event, context):
pass
```
--------------------------------
### Curl Deployed Chalice API
Source: https://github.com/aws/chalice/blob/master/README.rst
Test your deployed Chalice API endpoint using curl. This command sends a GET request to the API.
```bash
curl https://endpoint/api
```
--------------------------------
### Get Connection Properties
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wschat.md
Retrieves all properties associated with a given connection ID from the DynamoDB table. It queries all records for a connection and formats them into a dictionary.
```python
def get_record_by_connection(self, connection_id):
"""Get all the properties associated with a connection.
Each connection_id creates a partition in the table with multiple
SK entries. Each SK entry is in the format {property}_{value}.
This method reads all those records from the database and puts them
all into dictionary and returns it.
:param connection_id: The connection to get properties for.
"""
r = self._table.query(
KeyConditionExpression=(
Key('PK').eq(connection_id)
),
Select='ALL_ATTRIBUTES',
)
r = {
entry['SK'].split('_', 1)[0]: entry['SK'].split('_', 1)[1]
for entry in r['Items']
}
return r
```
--------------------------------
### Get User Entry from DynamoDB
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/todo-app/index.md
Retrieves a user's record from the DynamoDB 'Users' table using their username. This is a prerequisite for login authentication.
```default
$ python users.py --get-user myusername
Entry for user: myusername
hash : sha256
username : myusername
hashed : Hym8Ss6WIArus+aZ6BucZ3sz6Wu5w8Tc3lPUivTuUi4=
salt : rXMPBx8ZriKU3SQTh58BlxQQtpcLHfmITTB2tpRs/sM=
rounds : 100000
```
--------------------------------
### Default App Structure
Source: https://github.com/aws/chalice/blob/master/docs/source/topics/packaging.md
Illustrates the typical file and directory structure of a Chalice application before packaging.
```text
.
├── app.py
├── chalicelib
│ ├── __init__.py
│ └── utils.py
├── requirements.txt
└── vendor
├── myimage.png
└── internalpackage
└── __init__.py
```
--------------------------------
### Route Message to Command or Text Handler
Source: https://github.com/aws/chalice/blob/master/docs/source/tutorials/wschat.md
Determines if an incoming message is a command (starts with '/') or a text message and routes it to the appropriate handler.
```python
def _handle_message(self, connection_id, message, record):
# ... (docstring omitted for brevity) ...
if message.startswith('/'):
self._handle_command(connection_id, message[1:], record)
else:
self._handle_text(connection_id, message, record)
```
--------------------------------
### Configure Python Virtual Environment
Source: https://github.com/aws/chalice/blob/master/docs/source/samples/media-query/index.md
Create and activate a Python 3 virtual environment for the project. This ensures dependencies are isolated.
```bash
$ python3 -m venv /tmp/venv37
$ . /tmp/venv37/bin/activate
```