V2 API Python helper class

Here’s a basic Python class to get you up and running against the GraphQL API in V2:

from gql import Client
from gql.transport.requests import RequestsHTTPTransport

class Sonar:
    """This is a simple class for accessing the GraphQL API in Sonar V2.
    
    Args:
        sonar_url: The full URL to the GraphQL endpoint.
            Ex: https://instance.sonar.software/api/graphql
        token: The Personal Access Token of the user that will access the API.
    """
    
    def __init__(self, sonar_url, token):
        self.client = Client(
            transport=RequestsHTTPTransport(
                url=sonar_url,
                headers={
                    'Authorization': 'Bearer ' + token
                }
            )
        )

    def execute(self, query, variable_values=None):
        return self.client.execute(query, variable_values=variable_values)

Example usage:

from gql import gql
sonar = Sonar('https://example.sonar.software/api/graphql', 'secret.token')

sonar.execute(gql("""{
    accounts {
        entities {
            id
        }
    }
}"""))
# {
#   'accounts': {
#     'entities': [
#       { 'id': '1' },
#       { 'id': '2' },
#       ...
#     ]
#   }
# }

# Note: Int64Bit scalars are returned from the API as string

Maybe someone will find it useful.

2 Likes

Thank you - this will save me some work in the next few months.