Skip to main content
GraphQL

Fragments

QueryParseValidateMedium

What you will learn

  • Fragment reuse reduces duplication AND enables type-safe code generation โ€” prefer them
  • Inline fragments on union types must cover all members โ€” missing case = runtime error
  • Test fragment composition: nested fragments must merge fields without conflict

Description

Reuse field selections with fragments.

Test Scenario

const query = `
  fragment UserFields on User {
    id
    name
    email
  }

  query {
    user(id: "1") {
      ...UserFields
    }
    users {
      ...UserFields
    }
  }
`;
Endpoint/api/graphql

Testing Tips

  • โ€ขDefine fragment on specific type
  • โ€ขSpread with ... FragmentName
  • โ€ขReduces query duplication
// 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-fragments

2 frameworks available

API Playground

Send requests and inspect responses

Endpoint: /api/graphql

Press Enter to send