LoginSignup
0
1

More than 5 years have passed since last update.

[Python3] ApiGateway -> AWSLambdaをローカルで実行

Last updated at Posted at 2017-06-02

はじめに

apigateway -> lambdaって作りでアプリケーションを作ることが多くなてきて、
コード書いて、アップロードして、api叩いてデバッグしてってめんどくさい、ローカルでもget postとかで開発したい!
ってことから作りました。
とりあえずクエリーパラメータとjsonを受け取れるところまで!

apigatewayとlambdaを設定する

他のサイトを参考にしてください

  • lambdaはこんなの

スクリーンショット 2017-06-02 17.28.06.png

lambda.py

def handler(event, context):

    res = {}
    res['method'] = event['context']['http-method']
    res['url'] = event['params']['path']
    res['query-string'] = event['params']['querystring']
    res['json-body'] = event['body-json']

    return res
  • ApiGatewayのマッピングテンプレートはこんな感じ
#set($allParams = $input.params())
{
"body-json" : $input.json('$'),
"base64-body": "$util.base64Encode($input.body)",
"params" : {
#foreach($type in $allParams.keySet())
  #set($params = $allParams.get($type))
"$type" : {
  #foreach($paramName in $params.keySet())
  "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
      #if($foreach.hasNext),#end
  #end
}
  #if($foreach.hasNext),#end
#end
},
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
  #if($foreach.hasNext),#end
#end
},
"context" : {
  "http-method": "$context.httpMethod",
  }
}

これをローカルで開発したい!

dockerを使って開発環境を作る
githubに上げてあります。

docker build

docker-compose build

docker run

docker-compose up

lambdaを動かす

localhostの:80にアクセスするとlambda.pyが動きます

#GET
curl localhost/aaa?a=1

{
    "json-body": {},
    "method": "GET",
    "query-string": {
        "a": "1"
    },
    "url": "/aaa"
}


#POST
curl -H "Content-type: application/json" -X POST -d '{"a":1,"b":2}' localhost/aaa

{
    "json-body": {
        "a": "1",
        "b": "2"
    },
    "method": "POST",
    "query-string": {},
    "url": "/aaa"
}

今後

urlパラメータも取れるようにします

0
1
1

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
0
1