Skip to content

GraphQL

Arun Prakash edited this page Sep 28, 2025 · 1 revision

GraphQL (WPGraphQL) Support

This library now includes a minimal, type-safe GraphQL interface built on top of the existing requester, auth, middlewares, and responses.

Supported plugin: WPGraphQL (canonical). Default endpoint: /graphql.

Endpoint resolution

The GraphQL endpoint is derived from the REST base:

  • REST: https://example.com/wp-json/wp/v2 β†’ GraphQL: https://example.com/graphql
  • REST: https://example.com/blog/wp-json/wp/v2 β†’ GraphQL: https://example.com/blog/graphql

For custom setups, you can override the path:

client.graphql.setEndpointPath('/custom-graphql');

Usage

final client = WordpressClient.forSite(
  siteUrl: Uri.parse('https://example.com'),
  bootstrapper: (b) => b
    .withDefaultAuthorization(
      // Works with any existing auth (App Passwords / JWT, etc.)
      WordpressAuth.appPassword(user: 'user', appPassword: 'xxxx-xxxx'),
    )
    .build(),
);

final res = await client.graphql.query<List<Map<String, dynamic>>>(
  document: '''
    query Posts($limit: Int!) {
      posts(first: $limit) { nodes { id title } }
    }
  ''',
  variables: {'limit': 5},
  parseData: (data) {
    final nodes = (data['posts']?['nodes'] as List<dynamic>? ?? const [])
        .cast<Map<String, dynamic>>();
    return nodes;
  },
);

switch (res) {
  case WordpressSuccessResponse():
    print(res.data);
  case WordpressFailureResponse():
    print('Error: ${res.error}');
}

Mutations

Mutations use the same API as queries:

final result = await client.graphql.mutate<bool>(
  document: '''
    mutation UpdateSettings($title: String!) {
      updateSettings(input: { generalSettingsTitle: $title }) {
        clientMutationId
      }
    }
  ''',
  variables: { 'title': 'New Title' },
  requireAuth: true,
  parseData: (data) => true,
);

Raw GraphQL

If you want the raw response envelope ({ data, errors }) as-is:

final raw = await client.graphql.raw(
  document: '{ __typename }',
);

// raw is WordpressRawResponse; access raw.data
print(raw.data);

Authentication

GraphQL requests flow through the same authorization pipeline as REST requests.

  • Set a default authorization at bootstrap (App Passwords, JWT, etc.).
  • Or pass a specific authorization per call.
await client.graphql.query(
  document: '{ viewer { id name } }',
  requireAuth: true,
);

Errors

  • HTTP/network failures return WordpressFailureResponse with WordpressError.
  • GraphQL errors array is mapped to a single WordpressFailureResponse with code graphql_error and concatenated messages.

Tips

  • For maximum type-safety, define small model parsers and pass them via parseData.
  • You can still use middlewares, caching, and statistics with GraphQL requests.
Clone this wiki locally