5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【AWS】PythonでAppSync(GraphQL)を叩く

Last updated at Posted at 2021-09-30

#やりたいこと

とりあえずAppSync上にGraphQL APIは構築したが、まずはローカルで試してみたいorデータを一括登録したいという場合があると思いますので、boto3を使ってローカル環境でAPIを叩けるようなコードを作成しました。
ぜひ、ご活用ください。

#ソースコード

from requests_aws4auth import AWS4Auth
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
import pprint
import openpyxl
import sys
import json
import random
args = sys.argv

#一時的な利用なのでソースコード内に記述していますが、なるべく環境変数にしましょう。※補足参照
auth = AWS4Auth(
    "アクセスキー",
    "シークレットアクセスキー",
    "リージョン",
    "appsync",
)
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
}

#graphqlのURL
transport = RequestsHTTPTransport(
    url="https://xxxx.appsync-api.ap-northeast-1.amazonaws.com/graphql",
    use_json=True,
    headers=headers,
    auth=auth
)
client = Client(transport=transport, fetch_schema_from_transport=True)


def create_data(params):
    create = """
  mutation CreateData(
    $input: CreateDataInput!
    $condition: ModelDataConditionInput
  ) {
    createData(input: $input, condition: $condition) {
      id
      ...
      }
    }
  }
        """
    try:
        resp = client.execute(
            gql(create), variable_values=json.dumps({"input": params}))
    except:
        pprint.pprint(resp)

def main();
    params = {
      id: 12345,
      ...
    }
    create_data(params)

if __name__ == "__main__":
    main()

#補足
boto3を利用する際の認証情報に関しては以下をご参考ください。
公式:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html

Qiita:https://qiita.com/tsukamoto/items/00ec8ef7e9a4ce4fb0e9

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?