What's the difference between Operation Arguments and GraphQL variables?
Asked Answered
A

1

6

I am in the process of learning GraphQL and have stumbled upon understanding the difference between Operation Arguments and GraphQL variables. Because IMO, both provide, client, the facility to pass in dynamic data to either mutations or queries etc.

Can someone enlighten me ?

Cheers!

Aufmann answered 2/4, 2019 at 11:8 Comment(0)
A
7

Arguments and variables serve completely different functions.

Every field in a GraphQL schema can be configured to accept one or more arguments. For example:

query FilmQuery {
  film (id: "ZmlsbXM6MQ==") {
    id
    title
  }
}

Here the film field accepts an argument named id. Arguments are used to alter the value a field resolves to. In our example above, the server returns a different Film object based on the id value the client provides.

Arguments accept inputs, which can be either scalars, enums or more complex Input Object Types. Here, we're passing a String value of "ZmlsbXM6MQ==" to the argument. By writing out the value inside the query, we are said to be using a literal value.

There is nothing wrong with using literal values in your queries, but when the value passed to the argument needs to be dynamic, we need something more -- we need variables.

Variables allow us to parameterize and reuse queries. Here's our example, rewritten using a variable:

query FilmQuery($myId: ID!) {
  film (id: $myId) {
    id
    title
  }
}

Variables must first be defined at the top of your document, as part of the operation definition. Here we've defined a single variable ($myId) and told GraphQL it's type is ID!. Once defined, variables can then be used anywhere inside the operation. The actual values of any variables used in your document must be sent along with the query itself when the client actually makes the request to the server.

Again, arguments only provide a way to change how a request is executed, while using variables as inputs to those arguments is what makes a particular query dynamic and reusable.

Please note that you could use string concatenation or template literals client-side to achieve a similar effect to what variables do. You should generally avoid doing so, however, because 1) it unnecessarily creates additional work for the client and 2) serializing inputs yourself, especially complex ones like Input Object Types, can quickly become complicated and error-prone.

Allergist answered 2/4, 2019 at 11:58 Comment(1)
This was the exact kind of answer I was looking for. Thanks a ton man!!! Cheers!Aufmann

© 2022 - 2024 — McMap. All rights reserved.