pythonのrequestsでAPIGateWayをAPIKeyを使って呼び出す
3765 ワード
概要
ローカルのpythonのプログラムからリクエストを送信してAPI Gateway を呼び出せるかを試してみました。
APIKeyを設定することで呼び出しを制限できるので呼び出しを制限することができます。
処理呼び出し用の画面でも作ってそこのアクセス制限をしてしまう方が楽な方が気もしますが・・・
APIGateWayの設定
呼び出すPythonのプログラム
- ↓のようにrequestsを使ってheadersにAPIKeyを設定すれば呼び出すことができます。
import requests
import traceback
if __name__ == "__main__":
try:
# APIKeyはAPIGatewayで確認したAPIKey
headers = {'x-api-key': 'APIKey'}
# xxxxxxxx の部分は各APIの値 /test2 の部分はリソース名を指定ここでは greet
url='https://xxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/default/test2'
# 成功のパターン
rSucess = requests.get(url, headers=headers)
print(rSucess.status_code)
print(rSucess.content)
# 失敗のパターン
rFail = requests.get(url)
print(rFail.status_code)
print(rFail.content)
except :
print(traceback.format_exc())
- 呼び出した結果は↓のように1つ目はapikeyがあるため結果が返ってきますが、2つ目はapikeyがないため失敗となります。
200
b'"Hello from Lambda!"'
403
b'{"message":"Forbidden"}'
Author And Source
この問題について(pythonのrequestsでAPIGateWayをAPIKeyを使って呼び出す), 我々は、より多くの情報をここで見つけました https://qiita.com/dmikita/items/cfa36cc2a92d8fc563e9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .