
Member-only story
How to Query in GraphQL
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
…