Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

graphql
arguments
parameter

What are different ways to pass an argument in GraphQL?

Mian Basam Ahmad

Field arguments

Fields are the building blocks of GraphQL documents. The user specifies the fields they want, and the schema resolves the data that matches the fields’ definitions. This is useful since it enables users to offer extra parameters to specify what information they need each field to find. Without field arguments, the system would be quite rigid.

Types of field arguments

A GraphQL user can supply argument values for an argument in one of two ways:

  1. Document literals
  2. Variables

Document literals

Values are embedded directly inside the GraphQL document using document literals. It’s a simple method that works well with static documents.

The following is a query that retrieves menu items whose names match pizza by using a document literal for the matching argument:

{
  menuItems(matching: "pizza"){
      name
  }
}
GraphQL query

The literal for the string argument is in double quotation marks (""), and the argument values are provided after the argument name followed by a colon (:).

Using variables

Variables in GraphQL act as type placeholders for values that are sent with the request. This is a familiar concept to us if we’ve used parameterized SQL queries for value insertion and sanitization. Before they’re utilized with the operation type, GraphQL variables are specified with their types.

GraphQL operation

A GraphQL document is made up of one or more operations that represent something the GraphQL server should execute. Until now, we’ve been requesting the server to perform an information action known as a query in GraphQL. Additional operation types in GraphQL include mutation for persisting data changes and subscription for requesting a live data feed.

Declaring variables

Variable declarations are inserted inside a set of parentheses before the curly braces that begin the body of an operation. After a colon (:) and a space character, variable names begin with a dollar sign () and their GraphQL types follow. If we’re declaring many variables, we use commas to distinguish between them.

query ($term: String) { 
   menuItems(matching: $term) {
      name 
  }
}
Variables declaration in query

In the code above, we use the String type for our $term variable since that’s exactly the type of argument value that we defined for the matching argument in our schema.

query ($term: String) { 
  menuItems(matching: $term) {
    name 
  }
}
# Query variable
{"term":"pizza"}
GraphQL query

We get the following result:

{
  "data":{
    "menuItems": [
      {
        "name": "Hot pizza"
      }
    ]
  }
}
GraphQL query result

RELATED TAGS

graphql
arguments
parameter

CONTRIBUTOR

Mian Basam Ahmad
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring