Skip to main content
GraphQL

Query with Variables

QueryParseValidateEasy

What you will learn

  • Use variables, never string interpolation โ€” concatenation invites injection and breaks caching
  • Verify non-null variables produce a validation error BEFORE execution, not at runtime
  • Test default values โ€” a missing optional variable uses the schema default, not null

Description

Use variables to make queries reusable and safe.

Test Scenario

const query = `
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
    }
  }
`;
const variables = { id: "1" };
const response = await request.post('/api/graphql', {
  data: { query, variables }
});
Endpoint/api/graphql

Testing Tips

  • โ€ขDefine variables with $ prefix
  • โ€ขPass variables separately from query
  • โ€ขPrevents injection attacks
// Playwright API Testing - GraphQL
import { test, expect } from '@playwright/test';
test('GraphQL query', async ({ request }) => {
const response = await request.post('/api/graphql', {
data: {
query: `
query {
users {
id
name
email
}
}
`
}
});
expect(response.ok()).toBeTruthy();
const { data } = await response.json();
expect(data.users).toBeDefined();
});

Challenge ID: graphql-query-variables

2 frameworks available

API Playground

Send requests and inspect responses

Endpoint: /api/graphql

Press Enter to send