RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
•
•
•
•
•
•
•
•
•
•
see@	http://www.restapitutorial.com/lessons/whatisrest.html
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
REST	API
Client
Mobile client
REST	API
GET /users HTTP/1.1
{"users": […]}
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
REST	API
Amazon
DynamoDB
Amazon	S3
Amazon	
CloudWatch
Auto Scaling group
Security group
Elastic Load
Balancing
Instance
REST API
Amazon
DynamoDB
Amazon	
CloudWatch
Amazon	S3
Amazon
DynamoDB
Amazon	
CloudWatch
Amazon API Gateway
AWS Lambda
Amazon	S3
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
Lambda.GetFunction(params: {'body': '', 'url': u'https://lambda.us-west-2.amazonaws.com/2015-03-31
IAM.GetRole(params: {'body': {'Action': u'GetRole', 'RoleName': u'helloworld7', 'Version': u'2010-
IAM.CreateRole(params: {'body': {'Action': u'CreateRole', 'RoleName': u'helloworld7', 'Version': u
IAM.PutRolePolicy(params: {'body': {'Action': u'PutRolePolicy', 'RoleName': u'helloworld7', 'Polic
Lambda.CreateFunction(params: (... omitted from logs due to size ...)
APIGateway.GetRestApis(params: {'body': '', 'url': u'https://apigateway.us-west-2.amazonaws.com/re
APIGateway.CreateRestApi(params: {'body': '{"name": "helloworld7"}', 'url': u'https://apigateway.u
APIGateway.GetResources(params: {'body': '', 'url': u'https://apigateway.us-west-2.amazonaws.com/r
APIGateway.PutMethod(params: {'body': '{"authorizationType": "NONE"}', 'url': u'https://apigateway
APIGateway.PutIntegration(params: {'body': '{"httpMethod": "POST", "requestTemplates": {"applicati
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"responseTemplates": {"application/json": ""}
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"selectionPattern": "ChaliceViewError.*", "re
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"selectionPattern": "BadRequestError.*", "res
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"selectionPattern": "NotFoundError.*", "respo
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"selectionPattern": "UnauthorizedError.*", "r
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"selectionPattern": "ForbiddenError.*", "resp
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"selectionPattern": "ConflictError.*", "respo
APIGateway.PutMethodResponse(params: {'body': '{"responseModels": {"application/json": "Empty"}}',
APIGateway.PutIntegrationResponse(params: {'body': '{"selectionPattern": "TooManyRequestsError.*",
Lambda.GetPolicy(params: {'body': '', 'url': u'https://lambda.us-west-2.amazonaws.com/2015-03-31/f
Lambda.AddPermission(params: {'body': '{"Action": "lambda:InvokeFunction", "StatementId": "1e96468
APIGatewayCreateDeployment(params: {'body': '{"stageName": "dev"}', 'url': u'https://apigateway.us
API
# AWS SAM
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
https://github.com/aws/chalice
•
•
•
•
•
•
•
$ pip install chalice
$ chalice new-project helloworld && cd helloworld
$ cat app.py
from chalice import Chalice
app = Chalice(app_name="helloworld")
@app.route("/")
def index():
return {"hello": "world"}
$ chalice deploy
...
https://endpoint/api
$ curl https://endpoint/api
{"hello": "world"}
$ git diff
from chalice import Chalice
+import boto3
app = Chalice(app_name='chalice-sample')
+S3 = boto3.client('s3', region_name='us-east-1')
@app.route('/')
def index():
+ S3.get_object(Bucket = BUCKET, Key = key)
return {'hello': 'world'}
$ chalice deploy
Creating role: chalice-sample-dev
The following execution policy will be used:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": ["*"],
"Sid": "40e10c45a..."
},
...
}
Would you like to continue? [Y/n]:
$ chalice local
Serving on localhost:8000
$ npm install -g nodemon
$ nodemon --exec "chalice local" --watch *.py
[nodemon] 1.12.5
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: app.py
[nodemon] starting `chalice local`
Serving on localhost:8000
see@	https://qiita.com/TakenoriHirao/items/69f2af5aaf64db77124b
•
•
•
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
# Basic Definition
@app.route('/')
def index():
return {"GET": "/"}
# Specify Methods
@app.route('/', methods=['PUT'])
def index_put():
return {"PUT": "/"}
@app.route('/res', methods=['GET', 'POST'])
def my_resource():
request = app.current_request
if request.method == 'GET':
return {"GET": "/res"}
elif request.method == 'POST':
return {"POST": "/res"}
# Path Params
@app.route('/myresources/{object_name}')
def my_resource_key(object_name):
try:
response = S3.get_object(
Bucket = BUCKET, Key = object_name)
return response['Body'].read()
except ClientError as e:
raise e
@app.route('/s3/{bucket_name}/objects')
def objects_of(bucket_name):
try:
response =
S3.list_objects_v2(Bucket=bucket_name,
Prefix = S3_PREFIX)
objects = list(map(lambda x: x["Key"],
response["Contents"]))
return {"objects": objects}
except ClientError as e:
raise ...
@app.route('/')
def index():
return Response(
body = 'hello world!',
status_code = 200,
headers = {'Content-Type': 'text/plain'}
)
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
@app.route('/',
cors=True,
api_key_required=True,
authorizer=IAMAuthorizer())
def index():
return "yey"
@app.schedule(Rate(1,	unit=Rate.HOURS))
def every_hour(event):
print(event.to_dict())
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
•
•
•
•
•
class Chalice(object):
def route(self, path, **kwargs): #
def _register_view(view_func):
self._add_route(path, view_func, **kwargs)
return view_func
return _register_view
def _add_route(self, path, view_func, **kwargs):
methods = kwargs.pop('methods', ['GET'])
...
for method in methods:
...
entry = RouteEntry(view_func, name,
path, method, api_key_required, content_types, cors,
authorizer)
self.routes[path][method] = entry
class Chalice(object):
def __call__(self, event, context): #
resource_path = event.get('requestContext',
{}).get('resourcePath')
http_method = event['requestContext']['httpMethod']
route_entry = self.routes[resource_path][http_method]
view_function = route_entry.view_function
function_args = {name: event['pathParameters'][name]
for name in route_entry.view_args}
...
response = self._get_view_function_response(view_function,
function_args)
response_headers = CaseInsensitiveMapping(response.headers)
...
response = response.to_dict(self.api.binary_types)
return response
class Chalice(object):
def _get_view_function_response(self, view_function, function_args):
try:
response = view_function(**function_args)
if not isinstance(response, Response):
response = Response(body=response)
self._validate_response(response)
except ChaliceViewError as e:
response = Response(...)
except Exception as e:
headers = {}
if self.debug:
...
else:
response = Response(..., status_code=500)
return response
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
https://speakerdeck.com/akitsukada/sabaresudewang-dao-webhuremuwakuwoshi-ufang-fa
https://www.slideshare.net/shimy_net/aws-79149218
https://www.slideshare.net/shimy_net/cloud-roadshow-2017-osaka
•
•
•
https://github.com/kislyuk/domovoi
@app.sns_topic_subscriber("bartender")
def tend(event, context):
message = json.loads(event["Records"][0]["Sns"]["Message"])
context.log(dict(beer="Quadrupel", quantity=message["beer"]))
@app.cloudwatch_event_handler(source=["aws.ecs"])
def monitor_ecs_events(event, context):
message = json.loads(event["Records"][0]["Sns"]["Message"])
context.log("Got an event from ECS: {}".format(message))
@app.s3_event_handler(bucket="myS3bucket",
events=["s3:ObjectCreated:*"], prefix="foo", suffix=".bar")
def monitor_s3(event, context):
message = json.loads(event["Records"][0]["Sns"]["Message"])
context.log("Got an event from S3: {}".format(message))
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
•
•
•
•
•
•
•
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜

More Related Content

PDF
WordPress RESTful API & Amazon API Gateway (English version)
PDF
AWS における サーバーレスの基礎からチューニングまで
PDF
サーバーレスの現実と夢と今
PDF
A Crash Course on Serverless Applications in Python
PDF
Why your next serverless project should use AWS AppSync
PDF
Serverless in production, an experience report (London DevOps)
ODP
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
PDF
【AWS Developers Meetup】RESTful APIをChaliceで紐解く
WordPress RESTful API & Amazon API Gateway (English version)
AWS における サーバーレスの基礎からチューニングまで
サーバーレスの現実と夢と今
A Crash Course on Serverless Applications in Python
Why your next serverless project should use AWS AppSync
Serverless in production, an experience report (London DevOps)
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
【AWS Developers Meetup】RESTful APIをChaliceで紐解く

Similar to RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜 (20)

PPTX
Serverless solution architecture in AWS
PDF
AWS Community Day Bangkok 2019 - Build a Serverless Web Application in 30 mins
PDF
OpenStack API's and WSGI
PPTX
Aws serverless architecture
PPTX
Building self service framework
PDF
Aws Technical Day 2015 - Amazon API Gateway
PDF
ACDKOCHI19 - Building a serverless full-stack AWS native website
PDF
Building AWS native serverless website
PDF
Using Sinatra to Build REST APIs in Ruby
PPTX
AWS as platform for scalable applications
PPT
Intro to CloudStack API
PDF
2016-06 - Design your api management strategy - AWS - Microservices on AWS
PDF
Super lazy side projects - Hamik Mukelyan
PDF
Introduction to AWS
PPTX
StackMate - CloudFormation for CloudStack
PDF
Build an app on aws for your first 10 million users (2)
PDF
Auto scaling with Ruby, AWS, Jenkins and Redis
PPTX
Getting Started with Apache CloudStack
PPTX
Dissecting Open Source Cloud Evolution: An OpenStack Case Study
PDF
how to use openstack api
Serverless solution architecture in AWS
AWS Community Day Bangkok 2019 - Build a Serverless Web Application in 30 mins
OpenStack API's and WSGI
Aws serverless architecture
Building self service framework
Aws Technical Day 2015 - Amazon API Gateway
ACDKOCHI19 - Building a serverless full-stack AWS native website
Building AWS native serverless website
Using Sinatra to Build REST APIs in Ruby
AWS as platform for scalable applications
Intro to CloudStack API
2016-06 - Design your api management strategy - AWS - Microservices on AWS
Super lazy side projects - Hamik Mukelyan
Introduction to AWS
StackMate - CloudFormation for CloudStack
Build an app on aws for your first 10 million users (2)
Auto scaling with Ruby, AWS, Jenkins and Redis
Getting Started with Apache CloudStack
Dissecting Open Source Cloud Evolution: An OpenStack Case Study
how to use openstack api
Ad

More from 崇之 清水 (20)

PDF
知らなきゃ損なアップデートを振り返り(2020年分)- いにしえのサービスから勝手にチョイス
PDF
マイクロサービスを AWS サーバレス&コンテナで実装する方法
PDF
クラウドを活用したセンシング/モニタリングなどデータ分析の実現
PDF
AWS 主要なサービスアップデート 6/3-11/28
PDF
5分でサーバーレスの環境構築から本番デプロイまでやったろやないか! - Serverless Meetup Osaka #4 LT
PDF
サーバレスアプリケーションの入門と実践 - AWS Cloud Roadshow 2017 Osaka
PDF
データ分析 on AWS
PDF
日本語でおk AI スピーカーを作ってみた
PDF
Amazon Web Services (AWS) のご紹介
PDF
Amazon AI のスゴいデモ(仮) - Serverless Meetup Osaka
PDF
Amazon Pinpoint - re:Invent Serverless Follow Up - 20161207
PDF
AWS SDK for PHP のインストールから 始めるクラウドマスターへの道 〜 Promise による非同期オペレーション 〜
PDF
WordPress RESTful API & Amazon API Gateway - WordCamp Kansai 2016
PDF
Amazon API Gateway を活用したゲームサーバー構築
PDF
関西スタートアップAWS勉強会 スタートアップ最新事例
PDF
スタートアップ向け構成例とAWS活用事例(福岡市スタートアップカフェ)
PDF
Amazon Aurora の活用 - Developers.IO in OSAKA
PDF
SA プライムなう! - AWS IoT とロボットアームでお絵かき
PDF
Amazon Aurora の活用
PDF
CTO Night & Days 2015 Winter - AWS Mobile Testing
知らなきゃ損なアップデートを振り返り(2020年分)- いにしえのサービスから勝手にチョイス
マイクロサービスを AWS サーバレス&コンテナで実装する方法
クラウドを活用したセンシング/モニタリングなどデータ分析の実現
AWS 主要なサービスアップデート 6/3-11/28
5分でサーバーレスの環境構築から本番デプロイまでやったろやないか! - Serverless Meetup Osaka #4 LT
サーバレスアプリケーションの入門と実践 - AWS Cloud Roadshow 2017 Osaka
データ分析 on AWS
日本語でおk AI スピーカーを作ってみた
Amazon Web Services (AWS) のご紹介
Amazon AI のスゴいデモ(仮) - Serverless Meetup Osaka
Amazon Pinpoint - re:Invent Serverless Follow Up - 20161207
AWS SDK for PHP のインストールから 始めるクラウドマスターへの道 〜 Promise による非同期オペレーション 〜
WordPress RESTful API & Amazon API Gateway - WordCamp Kansai 2016
Amazon API Gateway を活用したゲームサーバー構築
関西スタートアップAWS勉強会 スタートアップ最新事例
スタートアップ向け構成例とAWS活用事例(福岡市スタートアップカフェ)
Amazon Aurora の活用 - Developers.IO in OSAKA
SA プライムなう! - AWS IoT とロボットアームでお絵かき
Amazon Aurora の活用
CTO Night & Days 2015 Winter - AWS Mobile Testing
Ad

Recently uploaded (20)

PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
CloudStack 4.21: First Look Webinar slides
PPT
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PPTX
Configure Apache Mutual Authentication
PDF
Flame analysis and combustion estimation using large language and vision assi...
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
PDF
Five Habits of High-Impact Board Members
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PPT
Module 1.ppt Iot fundamentals and Architecture
DOCX
Basics of Cloud Computing - Cloud Ecosystem
PPT
What is a Computer? Input Devices /output devices
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PPTX
Build Your First AI Agent with UiPath.pptx
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
A review of recent deep learning applications in wood surface defect identifi...
Enhancing plagiarism detection using data pre-processing and machine learning...
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Custom Battery Pack Design Considerations for Performance and Safety
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
CloudStack 4.21: First Look Webinar slides
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
sustainability-14-14877-v2.pddhzftheheeeee
Configure Apache Mutual Authentication
Flame analysis and combustion estimation using large language and vision assi...
OpenACC and Open Hackathons Monthly Highlights July 2025
Five Habits of High-Impact Board Members
sbt 2.0: go big (Scala Days 2025 edition)
Improvisation in detection of pomegranate leaf disease using transfer learni...
Module 1.ppt Iot fundamentals and Architecture
Basics of Cloud Computing - Cloud Ecosystem
What is a Computer? Input Devices /output devices
The influence of sentiment analysis in enhancing early warning system model f...
Build Your First AI Agent with UiPath.pptx
A contest of sentiment analysis: k-nearest neighbor versus neural network
A review of recent deep learning applications in wood surface defect identifi...

RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜