Filter Queries with Arguments
Basic Usage of Arguments in GraphQL Queries
In GraphQL, you can use arguments to apply filters and conditions to the requested data. To use an argument, you simply include it in the query by adding it in parentheses right after the field it is modifying. Arguments can be of different types, such as integers, strings, enums, etc., and are used to specify the exact conditions the server should consider when returning the data.
Previously, we used the countries
field with no arguments. Let's change the field to country
, which accepts an id
parameter to retrieve the information for a single country with the specified ID.
Filtering a query by ID
Let's say we want to get details only for the United States with the country code "US". We can do this by adding the id
argument and its value to our query like this:
{ country(id: "US") { id full_name_english available_regions { id name } } }
In this example, we use the id
argument and provide it the value of "US"
, which is the country code for the United States. Upon executing this query, the server will return details only for the specified country, making the result set smaller and more focused.
We can also pass arguments to nested fields. However, we cannot pass arguments into the available_regions
nested field because the API documentation tells us there are no accepted arguments for this field. This reminds us to always make sure to consult the documentation when working with arguments.
Using the field signature for argument details
Let's look at another example using the products
field. This field has several arguments that can be used to control the results:
GraphQL queries have signatures that also document all available arguments, each argument type, if it has a default value, and the type of data that is returned. The products
field can be represented with the following signature:
products( search: String filter: ProductAttributeFilterInput pageSize: Int = 20 currentPage: Int = 1 sort: ProductAttributeSortInput ): Products
Note that for this query, either the search
or filter
input argument is required. Arguments can also have default values, as shown above with pageSize
and currentPage
, which means you don't have to provide a value explicitly unless you want a different behavior.
Filtering a query by another argument
In this example, we will search for products containing the keyword "jacket". This will be done using the search
argument:
{ products(search: "jacket") { items { id name sku } } }
Upon executing this query, the server will return products with a name or description containing the word "jacket". This makes our search more precise and filters out unwanted results, giving us just the products we're interested in.
By using arguments, we can create queries that are tailored to our exact needs, giving us full control over the data returned by the server