LoginSignup
7
4

More than 3 years have passed since last update.

Chaliceを使ってお手軽APIを作成してみた

Last updated at Posted at 2019-09-18

Chalice って何?

AWSが提供しているものなのですが、READMEを見ると
AWS上にLambdaを使ったサーバレスアプリケーションを構築するためのPythonフレームワーク
というものだそう。

具体的に何ができるかというと、
・アプリケーションの作成、デプロイ、管理
・API Gateway, Amazon S3, Amazon SNS, Amazon SQSといったAWSサービスとの連携
・自動でIAMPolicy作成

なんかとても便利そう。

利用するための前提条件

・AWSにアカウントがあること
・AWSのAccessKey、SecretAccessKeyを作成していること
・pip(pythonのパッケージ管理ツール)がインストールされていること
・pythonのバージョンが2.7, 3.6, 3.7のいずれかであること(2019/8/23時点)

準備編

1. Chaliceのインストール

以下のコマンドを実行します。

$ sudo pip install chalice

本来は⬆️のコマンドでできるのですが
私の場合はsixのエラーが出たので、--ignore-installed sixをつけて再実行が必要でした。

$ sudo pip install chalice --ignore-installed six

これでSuccessfully InstalledとでたらOKです。

2. AWSCLIの認証情報を設定

LambdaとAPIGatewayをデプロイしたいAWS環境(test)のAccessKey、SecrettAccessKeyを設定します。
筆者は複数のAWSアカウントを利用しているため、以下のように記述しました。

~/.aws/credential
[test]
aws_access_key_id = {アクセスキー}
aws_secret_access_key = {シークレットキー}
~/.aws/config
[profile test]
output = json
region = {リージョン}

環境名の記述方法が両ファイルで異なるので、少し注意が必要です。

使ってみた編

まずは、プロジェクトを作成します。
今回はhelloworldというサンプルプロジェクトを作成してみます。

$ chalice new-project helloworld

作成したプロジェクトの構造をtreeコマンドで確認してみると、

$ tree -a helloworld
helloworld
├── .chalice
│   └── config.json
├── .gitignore
├── app.py
└── requirements.txt

必要なファイル一式が作成されていることが確認できます。
次に、作成されたapp.pyの中身を確認してみます。

$ cat helloworld/app.py
from chalice import Chalice

app = Chalice(app_name='helloworld')


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


 # The view function above will return {"hello": "world"}
 # whenever you make an HTTP GET request to '/'.
 #
 # Here are a few more examples:
 #
 # @app.route('/hello/{name}')
 # def hello_name(name):
 #    # '/hello/james' -> {"hello": "james"}
 #    return {'hello': name}
 #
 # @app.route('/users', methods=['POST'])
 # def create_user():
 #     # This is the JSON body the user sent in their POST request.
 #     user_as_json = app.current_request.json_body
 #     # We'll echo the json body back to the user in a 'user' key.
 #     return {'user': user_as_json}
 #
 # See the README documentation for more examples.
 #

すでにサンプルコードが記述されているので
このままプロジェクトをAWS上にデプロイしてみます。
 <注意>
 ・ --profile [AWS環境名]とすると、デプロイするAWS環境を指定することが可能
 ・ chalice deployコマンドは、作成したプロジェクトのルートディレクトリで実行する必要がある

$ cd helloworld
$ chalice deploy --profile test

デプロイに成功すると、以下のようなレスポンスが返ってきます。

Creating deployment package.
Creating IAM role: helloworld-dev
Creating lambda function: helloworld-dev
Creating Rest API
Resources deployed:
  - Lambda ARN: arn:aws:lambda:ap-southeast-1:xxxxxxxxxxxx:function:helloworld-dev
  - Rest API URL: https://xxxxxxxxxx.execute-api.ap-southeast-1.amazonaws.com/api/

Rest API URLが今回作成したAPIのURLなので、
返ってきたURLをCurlコマンドで叩いて確認します。

$ curl https://xxxxxxxxxx.execute-api.ap-southeast-1.amazonaws.com/api/
 {"hello":"world"}

hello worldと返ってきたので、無事作成完了です!

使ってみて

・LambdaとAPIGatewayの作成だけなら、chaliceそのものを使うのは比較的簡単
・ちょっと検証したい時とかに使えそう
・事前準備の方がハマりポイント多そう

参考

<複数環境でのAWSCLIの認証情報>
https://qiita.com/bakira/items/3a4876cbb39f9a7ec3b8

<Chaliceについて>
https://developer.feedforce.jp/entry/2017/11/11/210014#%E3%81%93%E3%81%93%E3%81%8C%E3%81%99%E3%81%94%E3%81%84%E3%81%9E-Chalice

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4