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.
A GraphQL user can supply argument values for an argument in one of two ways:
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}}
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 (:
).
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.
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.
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}}
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"}
We get the following result:
{"data":{"menuItems": [{"name": "Hot pizza"}]}}
Free Resources