/ #python #graphql 

Python GraphQL client requests example using gql

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'}]}}}

unsplash-logoIsis França

Author

Hugo Di Francesco

A developer, working out of London writing CSS, JavaScript and Python.

Subscribe to the Code with Hugo newsletter

Get the latest articles in your inbox every 2 weeks