0
3

More than 3 years have passed since last update.

python3でAPIをコールする。

Posted at

pythonのurllib.requestモジュールを用いてAPIをコールするメモ。

下準備

  • 適当なlambdaとAPI Gatewayを用意。

lambdaは受け取ったeventを返却するようにする。

import json

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': event
    }

API Gatewayでは各種メソッド(GET、POST、PUT)を用意。

  • メソッドリクエスト → APIキーの必要性trueに指定。
  • 統合リクエスト → lambda関数を指定。

[APIのデプロイ]を実行し、URIを取得。(API Gatewayで何かの更新をしたのなら都度デプロイすること!でないと反映されない。←めっちゃこれハマる。)

[使用量プラン]から[作成]を選び、APIステージを選択、レート・バースト・クォータを設定、APIキーを作成する。

本題のAPIを叩くlambda

import json
import urllib.request, urllib.error

request_url = "https://xxxx.execute-api.ap-northeast-1.amazonaws.com/stage"

api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"

def lambda_handler(event, context):
    headers = {'x-api-key': api_key, "Content-Type":"application/json"}

    request_json = {
        "key":"val"
    }

    req = urllib.request.Request(url=request_url, method="GET", headers=headers, data=json.dumps(request_json).encode())

    with urllib.request.urlopen(req) as res:
        body = res.read().decode()

    return json.loads(body)

参考

以下を加筆修正
https://qiita.com/j_tamura/items/5a22b102a58d1fa93a78

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