Github GraphQL Example
While Github GraphQL offers detailed documentation and an API Explorer, it doesn’t have (Python) code samples. Below is a basic GQL example. The query can be developed/tested in Explorer
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
import click
@click.command()
@click.option('--githubtoken', envvar="GITHUB_TOKEN", prompt=True, hide_input=True, help='Github token')
@click.option('--owner', help='Repository owner', required=True)
@click.option('--repository', help='Repository name', required=True)
def gh_query_repo(githubtoken, owner, repository):
transport=RequestsHTTPTransport(
url='https://api.github.com/graphql',
use_json=True,
headers={
"Authorization": f"Bearer {githubtoken}",
},
#verify=False,
retries=3,
)
client = Client(
transport=transport,
fetch_schema_from_transport=True,
)
query_repo = '''
query Repository($owner: String!, $repo: String!) {
repository(name: $repo, owner: $owner) {
id
}
}
''' // [^1]
result = client.execute(
gql(query_repo),
variable_values={
"owner": owner,
"repo": repository,
}
)
repositoryId = result['repository']['id']
print(repositoryId)
if __name__ == "__main__":
gh_query_repo()