![]() |
VOOZH | about |
We will use GraphQL API for demonstration. GraphQL is an open-source data query and manipulation language for APIs and a runtime for fulfilling queries with existing data. It's neither an architectural pattern nor a web service. GraphQL was developed internally by Facebook in 2012 before being publicly released in 2015.
Terms: Let's start by defining basic terms. For reference, consider the following sample operation.
👁 firstintroqueryGraphQL Operations: As a basic definition, anything that hits the server is called a 'query'. But formally, there are three types of Operations, and Query is just one of them and the other two are Mutations and Subscriptions. A string is written in the GraphQL language that defines one or more operations and fragments. We will use the ready-made example of Pokemon schema in this article you can also create your own schema.
GraphQL Query:A GraphQL query is used to read or fetch values. It is given to the GraphQL server for execution and a result is returned.
Fields: A unit of data that will be returned as part of a query response is known as a Fields, even if they are nested. The query structure and the result of that query's structure will be the same as you can see in the below diagram. Query:
{
pokemon(name:"pikachu") {
name
id
types
}
}
Output:
👁 Imagefield (argument name: argument type): returntype
Argument name is used to give the instruction about the required data which needs to be fetched whereas argument type specifies the kind of data that can be passed as the argument.
Arguments also help to resolve a query on the server-side in a specific way. It is a key:value pair supplied with a field. It can be a literal or a variable as well in the fields example we already used arguments on pokemon by providing specific name. Query:
{
pokemon(id:"UG9rZW1vbjowMDE") {
name
types
}
}
Output:
👁 Imagequery retrievePokemon{Output:👁 Image
firstPokemon: pokemon(name:"Pikachu") {
id
types
}
secondPokemon: pokemon(name:"Charizard") {
id
types
}
}
fragment basicInfoOfPokemon on Pokemon {Output:👁 Image
name
id
}
query retrievePokemon {
firstPokemon: pokemon(name: "pikachu") {
...basicInfoOfPokemon
types
weight{
minimum
maximum
}
classification
}
}
query Electrictype {Output:👁 Image
pokemon(name: "pikachu") {
name
weight {
minimum
maximum
}
}
}
fieldName @skip (if: booleanCondition) {Output:👁 Image
name
}
# The @skip acts like a default inclusion of
# The field, unless the 'if' is valid.
fieldName @include (if: booleanCondition) {Output:👁 Image
name
}
# The @include acts like a default exclusion of
# The field, unless the 'if' is valid.