Search code examples
pythongraphqlamazon-cognitoaws-appsync

How to call an AppSync mutation with Cognito authentication using python?


Is it possible to calling an AppSync mutation with Cognito authentication using Python? How?

I am trying to use boto3, but I don't found a way to execute graphql operations.

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/appsync.html


Solution

  • You can turn your API auth mode to be "API KEY" and call an AppSync mutation with http.

    For example.

    import requests
    import json
    
    APPSYNC_API_KEY = 'da2-xxxxxxxxxxxxx'
    APPSYNC_API_ENDPOINT_URL = 'https://xxxxxxxxxxxxx.appsync-api.us-west-2.amazonaws.com/graphql'
    
    headers = {
        'Content-Type': "application/graphql",
        'x-api-key': APPSYNC_API_KEY,
        'cache-control': "no-cache",
    }
    
    def execute_gql(query):
        payload_obj = {"query": query}
        payload = json.dumps(payload_obj)
        response = requests.request("POST", APPSYNC_API_ENDPOINT_URL, data=payload, headers=headers)
        return response
    

    Imagine you have a model called Items and you can easily make query like below:

    if __name__ == '__main__':
        print(execute_gql("query { listItems { items { id name } } }").json())
    

    Simply replace the string with the mutation operation.