So far we’ve been doing everything statically and that’s all fine and good. It makes queries quick to write and for websites which serve static pages to the client is very efficient. But what if we need some dynamic element, like say a dropdown menu from which a user can select a pizza or maybe a search bar where you can enter an ingredient and search for pizzas with that? In that case we need to make things dynamic and use GraphQL variables.
query GetPizza($name: Name) {
pizza(name: $name) {
name
price
ingredients {
name
}
}
}
{
"name": "Pepperoni"
}
This might look like excessive work, after all this will yield the exact same result as a query done statically (like the one we did before on the queries page). The key difference here is that now the only thing that needs changing is the variable. This way we can display data for different pizzas by changing just one line instead of constructing a whole new query. We can also do a lot more by combining GraphQL variables with directives.
Let’s say our restaurant is very inclusive and we have dedicated vegan options for our pizzas, where we switch ingredients for our vegan customers, who can also enjoy eating a nice and tasty pepperoni, just without animal products. For that we can use a simple directive which will skip one field and optionally include another:
query GetPizza($name: Name, $vegan: Boolean!) {
pizza(name: $name) {
name
price
ingredients @skip(if: $vegan) {
name
}
veganIngredients @include(if: $vegan) {
name
}
}
}
{
"name": "Pepperoni"
“vegan”: True
}
This way we have restructured the query to return different ingredients if the value vegan is true and get a vegan pepperoni pizza with zucchini, seitan or whatever else we like. We could do the same for price or we could simply skip certain ingredients when the vegan option is selected (for a poor man’s pizza with perhaps only tomato sauce and oregano)
Combining GraphQL variables and directives opens a lot more options skipping or including whatever we like. It should be fairly apparent that, even with just a small glimpse into GraphQL, a bit of simple restructuring can tailor the query to our exact needs. The key takeaway is flexibility and a very transparent structure, especially in contrast to REST. Looking at the amount of work needed to maintain and change a single, even very complex query, is still a lot easier than maintaining the entire data structure and multiple endpoints and queries with REST. True for more advanced purposes the query can become a lot more complex, but the overarching principle of getting everything we need with one query remains the same. It just requires a bit more specification for example by using things like GraphQL variables and directives.
Start the free trial and see all the features of GraphQL Editor yourself!