LoginSignup
15
17

More than 5 years have passed since last update.

AWS API Gateway x Lambda で jsonp を返却する

Last updated at Posted at 2016-04-16

普通に作ると jsonp にはできない

AWS API Gateway x Lambda x Python の API を作り、デフォルト設定のまま retuen で dict を返却すると自動的に json にパースされレスポンスが返る。
文字列を返すとクオートで囲まれてしまうので、 Lambda から直接 js を返却することができなかった。

例) callback({"hoge":"foo"}) を return すると "callback({\"hoge\":\"foo\"})" のように文字列としてレスポンスされてしまう。

やったこと

API Gateway レスポンスを加工する機能があったのでそれを利用した。
まずは Amazon API Gateway > APIs > hogeAPI > Resources > /foo から Method Execution を開く。

Method Response の設定

  1. Method Execution から Method Response を選択
  2. HTTP Status 200 を選択
  3. Response Models に application/javascript を追加
    Method Response.PNG

Integration Response の設定

  1. Method Execution から Integration Response を選択
  2. Method response status 200 を選択
  3. Body Mapping Templates を開く
  4. Content-Type application/json を開く
  5. 下記を入力する
BodyMappingTemplates
## format to jsonp
callback($input.json('$'))

Integration Response.PNG

まとめ

これで application/javascript で jsonp を返却することができるようになる。
データフローとしては以下のようになっている。

  1. Lambda から json を返却
  2. Integration Response で body を整形
  3. Method Response header を整形

BodyMappingTemplates をゴリゴリと作りこめば動的な callbak にも対応できそう。

参考

Amazon API Gateway – JSON形式のレスポンスをHTML形式に加工して返してみる

補足

API Gateway はデフォルト CORS が無効になっているので別途設定が必要です。

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