EN - GraphQL - Query GraphQL - GraphQL
EN - GraphQL - Query GraphQL - GraphQL
Landscape
Search docs...
Introduction
On this page, you'll learn in detail about how to query a GraphQL server.
Queries and
Mutations
Fields
Fields Arguments
Aliases
Fragments
At its simplest, GraphQL is about asking for speci c elds on objects. Operation Name
Let's start by looking at a very simple query and the result we get when Variables
Directives
we run it:
Mutations
Inline Fragments
{ {
hero { "data": { Schemas and
name "hero": {
} "name": "R2-D2" Types
} }
} Type System
} Type Language
Object Types and
Fields
You can see immediately that the query has exactly the same shape as Arguments
the result. This is essential to GraphQL, because you always get back The Query and
Mutation Types
what you expect, and the server knows exactly what elds the client is Scalar Types
asking for. Enumeration
Types
The eld name returns a String type, in this case the name of the main Lists and Non-
Null
hero of Star Wars, "R2-D2" .
Interfaces
Union Types
Oh, one more thing - the query above is interactive. That means you Input Types
can change it as you like and see the new result. Try adding an
Validation
https://graphql.org/learn/queries/ 1/14
10/16/2020 Queries and Mutations | GraphQL
appearsIn eld to the hero object in the query, and see the new Execution
result. Introspection
In the previous example, we just asked for the name of our hero which
BEST PRACTICES
returned a String, but elds can also refer to Objects. In that case, you can
make a sub-selection of elds for that object. GraphQL queries can Introduction
traverse related objects and their elds, letting clients fetch lots of related Thinking in
data in one request, instead of making several roundtrips as one would
Graphs
need in a classic REST architecture.
Serving over
{ { HTTP
hero { "data": {
Authorization
name "hero": {
# Queries can have comments! "name": "R2-D2", Pagination
friends { "friends": [
name { Global Object
} "name": "Luke Skywalker"
} }, Identi cation
} {
"name": "Han Solo" Caching
},
{
Note that in this example, the friends eld returns an array of items.
GraphQL queries look the same for both single items or lists of items,
however we know which one to expect based on what is indicated in the
schema.
Arguments
If the only thing we could do was traverse objects and their elds,
GraphQL would already be a very useful language for data fetching. But
when you add the ability to pass arguments to elds, things get much
more interesting.
{ {
human(id: "1000") { "data": {
name "human": {
height "name": "Luke Skywalker",
} "height": 1.72
https://graphql.org/learn/queries/ 2/14
10/16/2020 Queries and Mutations | GraphQL
} }
}
}
In a system like REST, you can only pass a single set of arguments - the
query parameters and URL segments in your request. But in GraphQL,
every eld and nested object can get its own set of arguments, making
GraphQL a complete replacement for making multiple API fetches. You
can even pass arguments into scalar elds, to implement data
transformations once on the server, instead of on every client separately.
{ {
human(id: "1000") { "data": {
name "human": {
height(unit: FOOT) "name": "Luke Skywalker",
} "height": 5.6430448
} }
}
}
Aliases
If you have a sharp eye, you may have noticed that, since the result object
elds match the name of the eld in the query but don't include
arguments, you can't directly query for the same eld with different
arguments. That's why you need aliases - they let you rename the result
of a eld to anything you want.
https://graphql.org/learn/queries/ 3/14
10/16/2020 Queries and Mutations | GraphQL
{ {
empireHero: hero(episode: EMPIRE) "data": {
name "empireHero": {
} "name": "Luke Skywalker"
jediHero: hero(episode: JEDI) { },
name "jediHero": {
} "name": "R2-D2"
} }
}
}
In the above example, the two hero elds would have con icted, but
since we can alias them to different names, we can get both results in
one request.
Fragments
Let's say we had a relatively complicated page in our app, which lets us
look at two heroes side by side, along with their friends. You can imagine
that such a query could quickly get complicated, because we would need
to repeat the elds at least once - one for each side of the comparison.
{ {
leftComparison: hero(episode: EMP "data": {
...comparisonFields "leftComparison": {
} "name": "Luke Skywalker",
rightComparison: hero(episode: JE "appearsIn": [
...comparisonFields "NEWHOPE",
} "EMPIRE",
} "JEDI"
],
fragment comparisonFields on Charac "friends": [
name {
appearsIn "name": "Han Solo"
friends { },
name {
} "name": "Leia Organa"
} },
{
https://graphql.org/learn/queries/ 4/14
10/16/2020 Queries and Mutations | GraphQL
"name": "C-3PO"
}
You can see how the above query would be pretty repetitive if the elds
were repeated. The concept of fragments is frequently used to split
complicated application data requirements into smaller chunks,
especially when you need to combine lots of UI components with
different fragments into one initial data fetch.
Operation name
Up until now, we have been using a shorthand syntax where we omit both
the query keyword and the query name, but in production apps it's useful
https://graphql.org/learn/queries/ 5/14
10/16/2020 Queries and Mutations | GraphQL
to use these to make our code less ambiguous.
query HeroNameAndFriends { {
hero { "data": {
name "hero": {
friends { "name": "R2-D2",
name "friends": [
} {
} "name": "Luke Skywalker"
} },
{
"name": "Han Solo"
}
The operation name is a meaningful and explicit name for your operation.
It is only required in multi-operation documents, but its use is encouraged
because it is very helpful for debugging and server-side logging. When
something goes wrong (you see errors either in your network logs, or in
the logs of your GraphQL server) it is easier to identify a query in your
codebase by name instead of trying to decipher the contents. Think of
this just like a function name in your favorite programming language. For
example, in JavaScript we can easily work only with anonymous
functions, but when we give a function a name, it's easier to track it down,
debug our code, and log when it's called. In the same way, GraphQL query
and mutation names, along with fragment names, can be a useful
debugging tool on the server side to identify different GraphQL requests.
Variables
https://graphql.org/learn/queries/ 6/14
10/16/2020 Queries and Mutations | GraphQL
So far, we have been writing all of our arguments inside the query string.
But in most applications, the arguments to elds will be dynamic: For
example, there might be a dropdown that lets you select which Star Wars
episode you are interested in, or a search eld, or a set of lters.
query HeroNameAndFriends($episode: {
hero(episode: $episode) { "data": {
name "hero": {
friends { "name": "R2-D2",
name "friends": [
} {
} "name": "Luke Skywalker"
} },
{
"name": "Han Solo"
VA R I AB LE S
},
{
{ "name": "Leia Organa"
"episode": "JEDI" }
} ]
}
Now, in our client code, we can simply pass a different variable rather
than needing to construct an entirely new query. This is also in general a
https://graphql.org/learn/queries/ 7/14
10/16/2020 Queries and Mutations | GraphQL
good practice for denoting which arguments in our query are expected to
be dynamic - we should never be doing string interpolation to construct
queries from user-supplied values.
Variable de nitions
The variable de nitions are the part that looks like ($episode: Episode)
in the query above. It works just like the argument de nitions for a
function in a typed language. It lists all of the variables, pre xed by $ ,
followed by their type, in this case Episode .
To learn more about the syntax for these variable de nitions, it's useful to
learn the GraphQL schema language. The schema language is explained
in detail on the Schema page.
Default variables
https://graphql.org/learn/queries/ 8/14
10/16/2020 Queries and Mutations | GraphQL
When default values are provided for all variables, you can call the query
without passing any variables. If any variables are passed as part of the
variables dictionary, they will override the defaults.
Directives
We discussed above how variables enable us to avoid doing manual
string interpolation to construct dynamic queries. Passing variables in
arguments solves a pretty big class of these problems, but we might also
need a way to dynamically change the structure and shape of our queries
using variables. For example, we can imagine a UI component that has a
summarized and detailed view, where one includes more elds than the
other.
VA R I AB LE S
{
"episode": "JEDI",
"withFriends": false
}
Try editing the variables above to instead pass true for withFriends ,
and see how the result changes.
https://graphql.org/learn/queries/ 9/14
10/16/2020 Queries and Mutations | GraphQL
speci cation includes exactly two directives, which must be supported by
any spec-compliant GraphQL server implementation:
Mutations
Most discussions of GraphQL focus on data fetching, but any complete
data platform needs a way to modify server-side data as well.
Just like in queries, if the mutation eld returns an object type, you can
ask for nested elds. This can be useful for fetching the new state of an
object after an update. Let's look at a simple example mutation:
mutation CreateReviewForEpisode($ep {
createReview(episode: $ep, review "data": {
stars "createReview": {
commentary "stars": 5,
} "commentary": "This is a grea
} }
}
}
VA R I AB LE S
https://graphql.org/learn/queries/ 10/14
10/16/2020 Queries and Mutations | GraphQL
{
"ep": "JEDI",
"review": {
"stars": 5,
"commentary": "This is a great
}
}
Note how createReview eld returns the stars and commentary elds
of the newly created review. This is especially useful when mutating
existing data, for example, when incrementing a eld, since we can
mutate and query the new value of the eld with one request.
You might also notice that, in this example, the review variable we
passed in is not a scalar. It's an input object type, a special kind of object
type that can be passed in as an argument. Learn more about input types
on the Schema page.
A mutation can contain multiple elds, just like a query. There's one
important distinction between queries and mutations, other than the
name:
While query elds are executed in parallel, mutation elds run in series,
one after the other.
Inline Fragments
Like many other type systems, GraphQL schemas include the ability to
de ne interfaces and union types. Learn about them in the schema guide.
https://graphql.org/learn/queries/ 11/14
10/16/2020 Queries and Mutations | GraphQL
If you are querying a eld that returns an interface or a union type, you will
need to use inline fragments to access data on the underlying concrete
type. It's easiest to see with an example:
VA R I AB LE S
{
"ep": "JEDI"
}
In this query, the hero eld returns the type Character , which might be
either a Human or a Droid depending on the episode argument. In the
direct selection, you can only ask for elds that exist on the Character
interface, such as name .
To ask for a eld on the concrete type, you need to use an inline fragment
with a type condition. Because the rst fragment is labeled as ... on
Droid , the primaryFunction eld will only be executed if the Character
returned from hero is of the Droid type. Similarly for the height eld for
the Human type.
Named fragments can also be used in the same way, since a named
fragment always has a type attached.
Meta elds
Given that there are some situations where you don't know what type
you'll get back from the GraphQL service, you need some way to
determine how to handle that data on the client. GraphQL allows you to
https://graphql.org/learn/queries/ 12/14
10/16/2020 Queries and Mutations | GraphQL
request __typename , a meta eld, at any point in a query to get the name
of the object type at that point.
{ {
search(text: "an") { "data": {
__typename "search": [
... on Human { {
name "__typename": "Human",
} "name": "Han Solo"
... on Droid { },
name {
} "__typename": "Human",
... on Starship { "name": "Leia Organa"
name },
} {
} "__typename": "Starship",
} "name": "TIE Advanced x1"
}
]
}
In the above query, search returns a union type that can be one of three
options. It would be impossible to tell apart the different types from the
client without the __typename eld.
GraphQL services provide a few meta elds, the rest of which are used to
expose the Introspection system.
Continue Reading →
https://graphql.org/learn/queries/ 13/14
10/16/2020 Queries and Mutations | GraphQL
Query Language Clients Stack Over ow GraphQL Foundation
Best Practices
Copyright © 2020 The GraphQL Foundation. All rights reserved. The Linux Foundation has registered
trademarks and uses trademarks. For a list of trademarks of The Linux Foundation, please see our
Trademark Usage page. Linux is a registered trademark of Linus Torvalds. Privacy Policy and Terms of Use.
https://graphql.org/learn/queries/ 14/14