3
2

More than 1 year has passed since last update.

Lambdaから外部APIへの接続方法(Python)

Last updated at Posted at 2022-12-15

概要

Lambdaから外部のAPIに接続するPythonコードを紹介します。

前提条件

コード

  import requests
  import json

  ip = <接続先のアドレス>

  def lambda_handler(event, context):
      url = "http://{}".format(ip)
      headers = {'content-type': 'application/json; charset=UTF-8'}
      payload = {<送りたい値>}
      
      res = requests.post(
          url,
          data=json.dumps(payload), 
          headers=headers
      )

      return res.json()

おまけ

認証情報をAPIに送りたい場合は、下記のようにheadersにAuthorizationを記述します。

  import requests
  import json

  ip = <接続先のアドレス>
  token = <アクセストークン情報>

  def lambda_handler(event, context):
      url = "http://{}".format(ip)
      headers = {'Authorization': 'Bearer {}'.format(token)}
      payload = {<送りたい値>}
      
      res = requests.post(
          url,
          data=json.dumps(payload), 
          headers=headers
      )

      return res.json()

おわりに

リクエストで仮に404などエラーが返ってきた場合、上記のコードでは、Lambdaは正常に終了します。

そのため、エラー時の処理を書きたい場合は、返ってきた値によってエラーを出すよう記述する必要があります。

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