Pass user input into a GraphQL API call
Problem
You have user input from a UI component that needs to be used in a GraphQL API call.
Solution
To pass user input from the client to a GraphQL API request use GraphQL variables and interpolation.
- Add the UI component on your Page or Component (e.g. an Input named
input
) - Create a new Page Function and select Make a GraphQL Request
- Jump to the GraphQL Resource by clicking the > next to the resource name, and configure your Base URL and Headers
- Enter the Query for the request and include a GraphQL $variableName:
query MyQuery($variableName: String!) {
__typename
// ... rest of GraphQL query, using $variableName
}
- Enter the following in variables to bind the input value to the $variableName:
{
variableName: {{ input.value }}
}
- Save and test your function
Discussion
- Binding expressions within the double curly braces can contain any valid ES2020 expression. The expression is always evaluated client-side first and sent to the server for proxying.
- Since all requests are proxied by the backend, you do not have to consider CORS / CSP headers.
- You can configure the resource’s base path and default headers in the GraphQL Resource’s settings.
- Avoid putting secrets such as Authorization header tokens in headers directly. Instead, use secrets using the
${{ MY_SECRET }}
syntax.