(Updated: )
/ #python #graphql #web development 

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

Co-author of "Professional JavaScript", "Front-End Development Projects with Vue.js" with Packt, "The Jest Handbook" (self-published). Hugo runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon, Elsevier and (currently) Eurostar.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.