GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||
GeezerVison is showing chalice.readthedocs.io — Quickstart and Tutorial — Python Serverless Microframework for AWS 1.15.1 documentation Quickstart and Tutorial¶In this tutorial, you’ll use the To install Chalice, we’ll first create and activate a virtual environment in python3.7: $ python3 --version Python 3.7.3 $ python3 -m venv venv37 $ . venv37/bin/activate Next we’ll install Chalice using $ python3 -m pip install chalice You can verify you have chalice installed by running: $ chalice --help Usage: chalice [OPTIONS] COMMAND [ARGS]... ... Credentials¶Before you can deploy an application, be sure you have credentials configured. If you have previously configured your machine to run boto3 (the AWS SDK for Python) or the AWS CLI then you can skip this section. If this is your first time configuring credentials for AWS you can follow these steps to quickly get started: $ 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) If you want more information on all the supported methods for configuring credentials, see the boto3 docs. Creating Your Project¶The next thing we’ll do is use the $ chalice new-project helloworld This will create a $ cd helloworld $ ls -la drwxr-xr-x .chalice -rw-r--r-- app.py -rw-r--r-- requirements.txt You can ignore the Let’s take a look at the from chalice import Chalice app = Chalice(app_name='helloworld') @app.route('/') def index(): return {'hello': 'world'} The Deploying¶Let’s deploy this app. Make sure you’re in the $ chalice deploy ... Initiating first time deployment... https://qxea58oupc.execute-api.us-west-2.amazonaws.com/api/ You now have an API up and running using API Gateway and Lambda: $ curl https://qxea58oupc.execute-api.us-west-2.amazonaws.com/api/
{"hello": "world"}
Try making a change to the returned dictionary from the For the rest of these tutorials, we’ll be using $ http https://qxea58oupc.execute-api.us-west-2.amazonaws.com/api/
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 18
Content-Type: application/json
Date: Mon, 30 May 2016 17:55:50 GMT
X-Cache: Miss from cloudfront
{
"hello": "world"
}
Additionally, the API Gateway endpoints will be shortened to
Next Steps¶You’ve now created your first app using The next few sections will build on this quickstart section and introduce you to additional features including: URL parameter capturing, error handling, advanced routing, current request metadata, and automatic policy generation. Tutorial: URL Parameters¶Now we’re going to make a few changes to our Our application so far has a single view that allows you to make
an HTTP GET request to from chalice import Chalice app = Chalice(app_name='helloworld') CITIES_TO_STATE = { 'seattle': 'WA', 'portland': 'OR', } @app.route('/') def index(): return {'hello': 'world'} @app.route('/cities/{city}') def state_of_city(city): return {'state': CITIES_TO_STATE[city]} In the example above, we’ve now added a GET /cities/seattle --> state_of_city('seattle') GET /cities/portland --> state_of_city('portland') Now that we’ve updated our $ chalice deploy Let’s try it out. Note the examples below use the $ 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"
}
Notice what happens if we try to request a city that’s not in our
$ http https://endpoint/api/cities/vancouver
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
X-Cache: Error from cloudfront
{
"Code": "ChaliceViewError",
"Message": "ChaliceViewError: An internal server error occurred."
}
In the next section, we’ll see how to fix this and provide better error messages. Tutorial: Error Messages¶In the example above, you’ll notice that when our app raised an uncaught exception, a 500 internal server error was returned. In this section, we’re going to show how you can debug and improve these error messages. The first thing we’re going to look at is how we can debug this issue. By default, debugging is turned off, but you can enable debugging to get more information: from chalice import Chalice app = Chalice(app_name='helloworld') app.debug = True The $ chalice deploy ... https://endpoint/api/ Now, when you request the same URL that returned an internal server error, you’ll get back the original stack trace: $ http https://endpoint/api/cities/vancouver
Traceback (most recent call last):
File "/var/task/chalice/app.py", line 304, in _get_view_function_response
response = view_function(*function_args)
File "/var/task/app.py", line 18, in state_of_city
return {'state': CITIES_TO_STATE[city]}
KeyError: u'vancouver'
We can see that the error is caused from an uncaught Now that we know the error, we can fix our code. What we’d like to do is catch this exception and instead return a more helpful error message to the user. Here’s the updated code: from chalice import BadRequestError @app.route('/cities/{city}') def state_of_city(city): try: return {'state': CITIES_TO_STATE[city]} except KeyError: raise BadRequestError("Unknown city '%s', valid choices are: %s" % ( city, ', '.join(CITIES_TO_STATE.keys()))) Save and deploy these changes: $ chalice deploy
$ http https://endpoint/api/cities/vancouver
HTTP/1.1 400 Bad Request
{
"Code": "BadRequestError",
"Message": "Unknown city 'vancouver', valid choices are: portland, seattle"
}
We can see now that we have received a * BadRequestError - return a status code of 400 * UnauthorizedError - return a status code of 401 * ForbiddenError - return a status code of 403 * NotFoundError - return a status code of 404 * ConflictError - return a status code of 409 * UnprocessableEntityError - return a status code of 422 * TooManyRequestsError - return a status code of 429 * ChaliceViewError - return a status code of 500 You can import these directly from the from chalice import UnauthorizedError Tutorial: Additional Routing¶So far, our examples have only allowed GET requests. It’s actually possible to support additional HTTP methods. Here’s an example of a view function that supports PUT: @app.route('/resource/{value}', methods=['PUT']) def put_test(value): return {"value": value} We can test this method using the $ http PUT https://endpoint/api/resource/foo
HTTP/1.1 200 OK
{
"value": "foo"
}
Note that the @app.route('/myview', methods=['POST', 'PUT']) def myview(): pass The above view function will be called when either an HTTP POST or
PUT is sent to Alternatively if you do not want to share the same view function across multiple HTTP methods for the same route url, you may define separate view functions to the same route url but have the view functions differ by HTTP method. For example: @app.route('/myview', methods=['POST']) def myview_post(): pass @app.route('/myview', methods=['PUT']) def myview_put(): pass This setup will route all HTTP POST’s to In the next section we’ll go over how you can introspect the given request in order to differentiate between various HTTP methods. Tutorial: Request Metadata¶In the examples above, you saw how to create a view function that supports an HTTP PUT request as well as a view function that supports both POST and PUT via the same view function. However, there’s more information we might need about a given request:
All of this and more is handled by the current request object that the
Let’s see an example of this. Suppose we want to create a view function that allowed you to PUT data to an object and retrieve that data via a corresponding GET. We could accomplish that with the following view function: 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) Save this in your # 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"
}
}
You might see a problem with storing the objects in a module level
The
Don’t worry about the @app.route('/introspect') def introspect(): return app.current_request.to_dict() Save this to your $ http 'https://endpoint/api/introspect?query1=value1&query2=value2' 'X-TestHeader: Foo'
HTTP/1.1 200 OK
{
"context": {
"apiId": "apiId",
"httpMethod": "GET",
"identity": {
"accessKey": null,
"accountId": null,
"apiKey": null,
"caller": null,
"cognitoAuthenticationProvider": null,
"cognitoAuthenticationType": null,
"cognitoIdentityId": null,
"cognitoIdentityPoolId": null,
"sourceIp": "1.1.1.1",
"userAgent": "HTTPie/0.9.3",
"userArn": null
},
"requestId": "request-id",
"resourceId": "resourceId",
"resourcePath": "/introspect",
"stage": "dev"
},
"headers": {
"accept": "*/*",
...
"x-testheader": "Foo"
},
"method": "GET",
"query_params": {
"query1": "value1",
"query2": "value2"
},
"raw_body": null,
"stage_vars": null,
"uri_params": null
}
Tutorial: Request Content Types¶The default behavior of a view function supports
a request body of You can also configure a view function to support other
content types. You can do this by specifying the
import sys from chalice import Chalice from urllib.parse import urlparse, parse_qs app = Chalice(app_name='helloworld') @app.route('/', methods=['POST'], content_types=['application/x-www-form-urlencoded']) def index(): parsed = parse_qs(app.current_request.raw_body.decode()) return { 'states': parsed.get('states', []) } There’s a few things worth noting in this view function.
First, we’ve specified that we only accept the
$ http POST https://endpoint/api/ states=WA states=CA --debug
...
>>> requests.request(**{'allow_redirects': False,
'headers': {'Accept': 'application/json',
'Content-Type': 'application/json',
...
HTTP/1.1 415 Unsupported Media Type
{
"message": "Unsupported Media Type"
}
If we use the $ http --form POST https://endpoint/api/formtest states=WA states=CA --debug
...
>>> requests.request(**{'allow_redirects': False,
'headers': {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
...
HTTP/1.1 200 OK
{
"states": [
"WA",
"CA"
]
}
The second thing worth noting is that parsed = parse_qs(app.current_request.raw_body)
Tutorial: Customizing the HTTP Response¶The return value from a chalice view function is serialized as JSON as the response body returned back to the caller. This makes it easy to create rest APIs that return JSON response bodies. Chalice allows you to control this behavior by returning an instance of
a chalice specific
Here’s an example of this: from chalice import Chalice, Response app = Chalice(app_name='custom-response') @app.route('/') def index(): return Response(body='hello world!', status_code=200, headers={'Content-Type': 'text/plain'}) This will result in a plain text response body: $ http https://endpoint/api/ HTTP/1.1 200 OK Content-Length: 12 Content-Type: text/plain hello world! Tutorial: GZIP compression for json¶The return value from a chalice view function is serialized as JSON as the response body returned back to the caller. This makes it easy to create rest APIs that return JSON response bodies. Chalice allows you to control this behavior by returning an instance of
a chalice specific
Here’s an example of this: import json import gzip from chalice import Chalice, Response app = Chalice(app_name='compress-response') app.api.binary_types.append('application/json') @app.route('/') def index(): blob = json.dumps({'hello': 'world'}).encode('utf-8') payload = gzip.compress(blob) custom_headers = { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' } return Response(body=payload, status_code=200, headers=custom_headers) Tutorial: CORS Support¶You can specify whether a view supports CORS by adding the
@app.route('/supports-cors', methods=['PUT'], cors=True) def supports_cors(): return {} Setting
The preflight request will return a response that includes:
If more fine grained control of the CORS headers is desired, set the
Code sample defining more CORS headers: from chalice import CORSConfig cors_config = CORSConfig( allow_origin='https://foo.example.com', allow_headers=['X-Special-Header'], max_age=600, expose_headers=['X-Special-Header'], allow_credentials=True ) @app.route('/custom-cors', methods=['GET'], cors=cors_config) def supports_custom_cors(): return {'cors': True} There’s a couple of things to keep in mind when enabling cors for a view:
from chalice import Chalice, Response app = Chalice(app_name='multipleorigincors') _ALLOWED_ORIGINS = set([ 'http://allowed1.example.com', 'http://allowed2.example.com', ]) @app.route('/cors_multiple_origins', methods=['GET', 'OPTIONS']) def supports_cors_multiple_origins(): method = app.current_request.method if method == 'OPTIONS': headers = { 'Access-Control-Allow-Method': 'GET,OPTIONS', 'Access-Control-Allow-Origin': ','.join(_ALLOWED_ORIGINS), 'Access-Control-Allow-Headers': 'X-Some-Header', } origin = app.current_request.headers.get('origin', '') if origin in _ALLOWED_ORIGINS: headers.update({'Access-Control-Allow-Origin': origin}) return Response( body=None, headers=headers, ) elif method == 'GET': return 'Foo'
The last point will change in the future. See this issue for more information. Tutorial: Policy Generation¶In the previous section we created a basic rest API that
allowed you to store JSON objects by sending the JSON
in the body of an HTTP PUT request to However, there’s a problem with the code we wrote: 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) We’re storing the key value pairs in a module level A better solution would be to store this information in Amazon S3. To do this, we’re going to use boto3, the AWS SDK for Python. First, install boto3: $ pip install boto3 Next, add $ pip freeze | grep boto3 >> requirements.txt The requirements.txt file should be in the same directory that contains
your import json import boto3 from botocore.exceptions import ClientError from chalice import NotFoundError S3 = boto3.client('s3', region_name='us-west-2') BUCKET = 'your-bucket-name' @app.route('/objects/{key}', methods=['GET', 'PUT']) def s3objects(key): request = app.current_request if request.method == 'PUT': S3.put_object(Bucket=BUCKET, Key=key, Body=json.dumps(request.json_body)) elif request.method == 'GET': try: response = S3.get_object(Bucket=BUCKET, Key=key) return json.loads(response['Body'].read()) except ClientError as e: raise NotFoundError(key) Make sure to change Manually Providing Policies¶IAM permissions can be auto generated, provided manually or can be pre-created and explicitly configured. To use a pre-configured IAM role ARN for chalice, add these two keys to your chalice configuration. Setting manage_iam_role to false tells Chalice to not attempt to generate policies and create IAM role. "manage_iam_role":false "iam_role_arn":"arn:aws:iam::<account-id>:role/<role-name>" Whenever your application is deployed using You can also run the $ chalice gen-policy
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:ListAllMyBuckets"
],
"Resource": [
"*"
],
"Effect": "Allow",
"Sid": "9155de6ad1d74e4c8b1448255770e60c"
}
]
}
Experimental Status¶The automatic policy generation is still in the early stages, it should
be considered experimental. You can always disable policy
generation with Additionally, you will be prompted for confirmation whenever the auto policy generator detects actions that it would like to add or remove: $ chalice deploy Updating IAM policy. The following action will be added to the execution policy: s3:ListBucket Would you like to continue? [Y/n]: Tutorial: Using Custom Authentication¶AWS API Gateway routes can be authenticated in multiple ways:
API Key¶@app.route('/authenticated', methods=['GET'], api_key_required=True) def authenticated(): return {"secure": True} Only requests sent with a valid X-Api-Key header will be accepted. Using AWS IAM¶authorizer = IAMAuthorizer() @app.route('/iam-role', methods=['GET'], authorizer=authorizer) def authenticated(): return {"secure": True} Using Amazon Cognito User Pools¶To integrate with cognito user pools, you can use the
authorizer = CognitoUserPoolAuthorizer( 'MyPool', header='Authorization', provider_arns=['arn:aws:cognito:...:userpool/name']) @app.route('/user-pools', methods=['GET'], authorizer=authorizer) def authenticated(): return {"secure": True} Note, earlier versions of chalice also have an Using Custom Authorizers¶To integrate with custom authorizers, you can use the authorizer = CustomAuthorizer( 'MyCustomAuth', header='Authorization', authorizer_uri=('arn:aws:apigateway:region:lambda:path/2015-03-31' '/functions/arn:aws:lambda:region:account-id:' 'function:FunctionName/invocations')) @app.route('/custom-auth', methods=['GET'], authorizer=authorizer) def authenticated(): return {"secure": True} Tutorial: Local Mode¶As you develop your application, you may want to experiment locally before
deploying your changes. You can use For example, if we have the following from chalice import Chalice app = Chalice(app_name='helloworld') @app.route('/') def index(): return {'hello': 'world'} We can run $ chalice local Serving on localhost:8000 We can override the port using: $ chalice local --port=8080 We can now test our API using $ http localhost:8000/
HTTP/1.0 200 OK
Content-Length: 18
Content-Type: application/json
Date: Thu, 27 Oct 2016 20:08:43 GMT
Server: BaseHTTP/0.3 Python/3.7.3
{
"hello": "world"
}
The Deleting Your App¶You can use the $ chalice delete --stage dev Deleting Rest API: duvw4kwyl3 Deleting function aws:arn:lambda:region:123456789:helloworld-dev Deleting IAM Role helloworld-dev
©2016, James Saryerwinnie.
|
Page source
| ||||||||||||||||||
| You are visitor 01402605 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |