
How to Query in GraphQL
The basics of GraphQL, Querying and more.
Who's this for ?- You need to learn how to query graphQL fast, maybe because your new project or prospective job needs you to.- You are comfortable with traditional rest APIs but can't get into graphQL.- You want Python/Javascript implementation examples.- You are curios about GraphQL.NOTE: This is not the right tutorial if you want to write or serve graphs via an API since I won't be covering that aspect, although I think it helps if you understand how to consume graphs first and some general theory, so this will also help you.
What is it ?
Big picture there’s data in a database somewhere and it can be made public/exposed via an API, traditionally you would be given an endpoint and syntax to query it via REST, something like api.yummysnacks/list_snacks
, then you use some javascript or python library to query it and you get a response, usually in JSON {snacks: {cupcake,cookie,icecream}}
you then use this information to do something useful like display it on a site or app’s front end.
GraphQL is simply another way to get this information ( a query language ), you are still given an API endpoint, something like api.yummysnacks
but how you ask for information is different, here’s what the previous request would look like as a graphQL query:
query {
snacks{
type
}
}
You would get this as a response:
{
"data": {
"snacks": [
{
"type": "cupcake"
},
{
"type": "cookie"
},
{
"type": "ice cream"
}
]
}
}
This might seem like a weird over complicated syntax, but the main benefit is that you have a fundamentally different, ( yet logical ) and dramatically expanded way to interact with data ( within limits though ), let me explain…
When you query via a REST API request you have no idea what you are getting, with graphQL you know; you asked for snack type
in the query, you got precisely snack type in the response. You can also ask only for the information you need, let’s say we wanted to also query for flavor
, we would just change our query to :
query {
snacks{
type
flavor
}
}
And get the following response:
{
"data": {
"snacks": [
{
"type": "cupcake",
"flavor": "blueberry"
},
{
"type": "cookie",
"flavor": "chocolate chip"
},
{
"type": "ice cream",
"flavor": "vanilla"
}
]
}
}
In comparison a REST api would include a predetermined set of attributes and you have no choice but to receive them along with your request.
A graph you say ?
Perhaps the most difficult thing to grasp when transitioning to GraphQL is the notion that you are dealing with a data graph on the other end of your queries and not static responses tied to particular requests, here you traverse the graph and get back tree objects; heavy stuff.

Your garden variety Graph consists of some nodes and edges, in graphQL your nodes represent data and the edges the relationship between said data, our query for instance would look like this:

And that is a tree we took out of a graph via a query.
Entry Points (or Root,Query types)If you look at both graphs, you might not see much of a similarity but that's because we need a place to start traversing the graph and that's what an entry point is :

So we could have asked the graph for a menu, snacks or beverages; these root query types are given to us by the graph itself which is what we will cover next.
We are mostly done with the theory, the following are more real world practical considerations, good place for a break if you need one.
Introspection and Schemas
A graphs schema is basically a map you can use to make queries and introspection is a way to ask a graph for said map.
Let’s say you are given an api endpoint and nothing else, your job is to build a front end dashboard, where do you start?
BTW where do you get a practice graph ? https://github.com/APIs-guru/graphql-apis : Public graphQL endpoint collection.https://thegraph.com/explorer/ : Crypto related graphs with built-in playground.
Most graphQL api endpoints lead you to a graphiQL (or similar ) interface like this one:
https://graphql.org/swapi-graphql

On the left you type your query, hit play ▶ and get a result, on the right you can find your schema starting (Usually) from the root or root nodes. You can traverse the graph schema by clicking these elements or searching.
My favorite way to get/understand a schema is through a graphical overview using GraphQL Voyager and introspection. Introspection is a way to ask a graph for its schema and Voyager makes it super easy:

- Go to the graphVoyager project demo and change the schema (1)
- Copy the introspection query into your GraphiQl dashboard (2)
- Copy/paste the response schema back into voyager (3)
- Finally click Display (4)Notes: You can build your own Voyager Graph Explorer ! Just fork or include it into your project, consult the github.
Sadly not all graphQL API's work ( use simple Introspection instead ), but those that do give you this:

You get a birds eye view of the graph you are querying, note the left zoomed Query which represents the entry points, if you compare that to our snacks graph it is fundamentally the same.
Armed with these tools and know how ( and some pen and paper ) you can plan most of your queries, let’s now look at some specific implementations and queries…
Client Libraries
So now you know how to get a schema and have some idea of how the query process works, now you need to get started on you project, you might need some middleware in the form of a graphQL client which there are plenty , we will try out a couple for Python and Javascript…
Python: gql
Install: pip install --pre gqlExample (HW_gql.py):from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransportsample_transport=RequestsHTTPTransport(
url='https://api.thegraph.com/subgraphs/name/graphprotocol/compound-v2',
verify=True,
retries=3,
)client = Client(
transport=sample_transport
)query = gql('''
query {
markets(first: 4) {
name
}
}
''')response = client.execute(query)print(response)>>>{'markets': [{'name': 'Compound Augur'}, {'name': 'Compound USD Coin'}, {'name': 'Compound Ether'}, {'name': 'Compound Dai'}]} ---------------------***---------------------Give this script a graphQL api url, a query and you are set, if you need more options consult the documentation but it is pretty straightforward stuff.
Javascript vanilla:const URL = 'https://api.thegraph.com/subgraphs/name/graphprotocol/compound-v2';let content = {
"query": `{
markets(first: 4) {
name
}
}`
};let body = JSON.stringify(content);fetch(URL, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: body
})
.then(response => response.json())
.then(data => {
document.body.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
});Code source :https://css-tricks.com/raw-graphql-querying/

For simple requests and this introduction this should work, but if you are working with node or a front end framework check the list of clients (and do a search, new ones pop up all the time):graphql-clients
Basic queries.
Now that we have the basic implementations covered it’s time to tackle some basic queries, all these queries should work in your client of choice but since every graph is a little different you should use your noodle to adapt them to your needs…
If for instance you want to get all the items from an entry point:query allItems{
items{
id
itemData
}
}
Note that we are naming our query now (allItems), but beyond that it is the same query we saw at the start, we are also assuming that the schema has a root query called items and that each item has an id along with some itemData
Traversal
If you want to go one (or many) levels deeper you can traverse your graph like so:query allItemsDataId{
items{
id
itemData{
id
}
}
}
Arguments
Lets say you want a specific item and the graph allows you to retrieve it, usually through and id field; your query would look like this:query specificThing{
item(id:"theThingsid"){
itemdata
}
}
Arguments beg the question where do you get arguments since every graph is different ? A few ways:

Here we are using the Uniswap graph...If you used the introspection query on voyager when you click on any root query you will get a field of arguments and their defaults, let's say you want the exchanges query arguments, those would be:(skip,first,orderBy,orderDirection,where,block)The arguments valid value can then be extracted if you open the exchanges field and select the argument, where in this case:

So in order to use the where: Exchange_filter
we would chose a value like say tokenSymbol
to filter for a specific token:
Graph source: https://thegraph.com/explorer/subgraph/graphprotocol/uniswap?query=Exchanges%20by%20volumequery whereClause{
exchanges(where: {tokenSymbol:"WBTC"}) {
id
price
priceUSD
tokenName
ethBalance
tokenAddress
tokenBalance
ethLiquidity
tokenLiquidity
tokenSymbol
tradeVolumeEth
}
}Run this query and you should get a specific exchange.
You can also find the arguments in your GraphiQL interface while typing your queries:

What’s next:
As a practical introduction I hope this helps you get started, there are a few more topics and graphQL features that I would point you to if you want to keep learning, these might also be needed for your project:
Mutations : Which allow you to change information in the graph.
Variables, fragments: We just scrapped what information you can use to compose your queries, variables and fragments help with complex requests.
Authentication: Some graphs require you to be authenticated to query and perform mutations.
Deeper Type & schema understanding.
Subscriptions: Get notified when a graph changes.
Serve a graph
Framework Integration
For more information on the above I would point you to the following links:
Thanks for reading !