Named queries and parameters
GraphQL supports variables and naming queries, which should always be used since they make the query more clear while reading.
Let’s look at an example. In the following snippet, GetCustomers
is a named query that returns a page associates. This query has three parameters: $companyNo
specifies the Visma.net company number that uniquely identifies the company within the system, $pageSize
the maximum number of records to be returned, and $after
the cursor that indicates the position after which the records are to be fetched. If nothing is specified, this means the first $pageSize
records are to be fetched.
query GetCustomers($companyNo: Int, $pageSize: Int, $after :String)
{
useCompany(no: $companyNo)
{
associate(first: $pageSize, after: $after)
{
totalCount
pageInfo
{
hasNextPage
hasPreviousPage
startCursor
endCursor
}
items
{
associateNo
customerNo
name
}
}
}
}
If you use GraphiQL, you can define the variables in the query variable pane in the lower left of the IDE, as shown in the following image:
When you perform the request to GraphQL programmatically, or from a tool that does not directly support GraphQL variables, you must put the request containing both the query and variables in the body, as application/json
.
{
"query" : "query GetCustomers($companyNo: Int, $pageSize: Int, $after :String)\n{\n useCompany(no: $companyNo)\n {\n associate(first: $pageSize, after: $after)\n {\n totalCount\n pageInfo\n {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n items\n {\n associateNo\n customerNo\n name\n }\n }\n }\n}",
"variables":"{\"companyNo\": 9112233,\"pageSize\": 5}"
}
Details about the raw form of a GraphQL query were presented in an earlier section of this tutorial.