Python GraphQL client requests example using gql

Hugo Di Francesco - Aug 27 '18 - - Dev Community

An example consuming a GraphQL API from Python using gql.

Full code example at HugoDF/python-graphql-client-example.

This was sent out on the Code with Hugo newsletter last Monday.Subscribe to get the latest posts right in your inbox (before anyone else).

$ pip install gql # You should use a virtualenv
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

_transport = RequestsHTTPTransport(
    url='https://graphql-pokemon.now.sh/',
    use_json=True,
)

client = Client(
    transport=_transport,
    fetch_schema_from_transport=True,
)
query = gql("""
{
    pokemon(name: "Pikachu") {
        attacks {
            special {
                name
            }
        }
    }
}
""")

print(client.execute(query))
$ python fetch.py
{'pokemon': {'attacks': {'special': [{'name': 'Discharge'}, {'name': 'Thunder'}, {'name': 'Thunderbolt'}]}}}

Isis França

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .