LoginSignup
7
7

More than 5 years have passed since last update.

ClojureとAWS Lambda, API GatewayでREST APIを作る

Posted at

APIの作成

API GatewayでAPIを作る。

aws apigateway create-rest-api --name hello-lambda-clojure

リソースの定義

リソースはツリー構造になっているので、新しくリソースを作るにはルートのリソースIDが必要。get-resourcesを使ってそのIDを確認する。

 aws apigateway get-resources --rest-api-id 0a5sxbe4gg
{
    "items": [
        {
            "path": "/",
            "id": "8s2bu30t65"
        }
    ]
}

今回は/greetings/helloにJSONをPOSTするとレスポンスを返すというAPIにしたいので、greetings, helloというリソースを作成する。

まず/greetingsを作成。

aws apigateway create-resource --rest-api-id 0a5sxbe4gg --path-part greetings --parent-id 8s2bu30t65
{
    "path": "/greetings",
    "pathPart": "greetings",
    "id": "ckagp3",
    "parentId": "8s2bu30t65"
}

続いて/greetings/helloを作成。

aws apigateway create-resource --rest-api-id 0a5sxbe4gg --path-part hello --parent-id ckagp3
{
    "path": "/greetings/hello",
    "pathPart": "hello",
    "id": "is2t79",
    "parentId": "ckagp3"
}

メソッドの定義

メソッドの定義をCLIを使ってやろうと頑張ったけど、ドキュメントが少なくそれっぽく出来てもよく分からないエラーになったので、諦めてAWSのWebコンソールで"Create Method"でメソッドを作り、"Integration Type"に"Lambda Function"を選択した。

Lambda Functionはこちらの記事に書いたような感じで予め作成してあります。

以下は結局うまくいかなかった作業ログ。

メソッドを作成。

aws apigateway put-method --rest-api-id 0a5sxbe4gg --resource-id is2t79 --http-method POST --authorization-type NONE
{
    "apiKeyRequired": false,
    "httpMethod": "POST",
    "authorizationType": "NONE"
}

メソッドに対するIntegrationを作成。

aws apigateway put-integration --rest-api-id 0a5sxbe4gg --resource-id is2t79 --http-method POST--type AWS --integration-http-method POST --uri arn:aws:apigateway:ap-northeast-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:YOUR_AWS_ACCOUNT_ID:function:hello-lambda/invocations
aws apigateway put-method-response --rest-api-id 0a5sxbe4gg --resource-id mdb71c --http-method POST --status-code 200 --response-models '{"application/json": "Empty"}'
aws apigateway put-integration-response --rest-api-id 0a5sxbe4gg --resource-id mdb71c --http-method POST --status-code 200 --response-templates '{"application/json": ""}'

デプロイ&テスト

ステージを作って、実際にAPIにアクセスしてみる。

aws apigateway create-deployment --profile development --rest-api-id 0a5sxbe4gg --stage-name sandbox

APIのURLはhttps://REST-API-ID.execute-api.REGION.amazonaws.com/STAGEというURLになるらしい。

curl -H 'Content-Type: application/json' -d '{"name": "Clojure"}' https://0a5sxbe4gg.execute-api.ap-northeast-1.amazonaws.com/sandbox/greetings/hello
{"message":"Hello Clojure"}

無事にAWS LambdaとAPI Gatewayを使った初めてのAPIを作れました。

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