What is GraphQL?
GraphQL is a query language for Your API, and a server-side runtime for executing your queries. It is not tied to any specific database engine it is up to you to resolve the query. To create a GraphQL service you define types and their fields, then provide functions for each field on each type.
GraphQL query language
A GraphQL query looks like this:
Everything inside the square brackets,
] is optional.
The return result will be something like this
GraphQL is about asking your service for specific fields from specific objects. For example: getting the name field from a user. The nice thing about GraphQL is the data you get is shaped exactly as the query.
change this to table side by side
A field can also refer an Object or a collection of Objects, for example let say every person in the database can have a pet. The query will look like this: change this to table side by side
In GraphQL every field and nested object can get its own set of arguments, this is very powerful, and sets GraphQL from REST apart.
So let's evolve our previous query a bit
Let me explain the previous query.
I told my service to get the user with the id
kdlhh123hf3tzf with the fields name and the height in meter. Using arguments you can specify things like the format of the field.
Let's take this example query
Graphql will give us an error
That's because we can't use the same node name twice similar to json. To solve that we can use GraphQL Aliases.
the result of this query will be
A graphql auery can get very verbose and Mainly because you need to provide every field you want to pull from your graphql endpoint. Using Graphql Fragment you can reuse pieces of query logic accross multiple queries. We can improve our previous query using fragment like this
What happened here is that we groupped the common fields on the User Object in a Fragment and we used it everytime we query for a user instead of writing the field names over and over again.