MockServer can mock GraphQL APIs in two complementary ways:

  1. Schema import — send a GraphQL SDL or introspection document to PUT /mockserver/graphql and MockServer generates one expectation per root operation type. Matched queries receive a schema-valid, synthesized {"data": {...}} response with no hand-authored JSON required.
  2. Explicit GraphQL expectations — write an expectation whose body matcher is a GRAPHQL body with a query string, operation name, or field list, giving precise control over which operations are matched and what response is returned.

GraphQL matching works on standard HTTP: a GraphQL request arrives as a POST to /graphql (or a configurable path) with the operation in the JSON body. MockServer does not require any protocol plugin — it matches and responds to GraphQL traffic using the same HTTP expectation mechanism as REST.

 

Schema Import — PUT /mockserver/graphql

The schema import endpoint parses a GraphQL SDL or introspection document and generates mock expectations automatically — one per root operation type (Query, Mutation, Subscription) defined by the schema.

Send the schema as the raw request body with Content-Type: application/graphql (for SDL) or Content-Type: application/json (for an introspection result):

# Import from SDL
curl -s -X PUT "http://localhost:1080/mockserver/graphql" \
  -H "Content-Type: application/graphql" \
  --data-raw '
type Query {
  user(id: ID!): User
  products(category: String): [Product]
}
type Mutation {
  createOrder(input: OrderInput!): Order
}
type User  { id: ID! name: String email: String }
type Product { id: ID! name: String price: Float inStock: Boolean }
type Order   { id: ID! status: String total: Float }
input OrderInput { productId: ID! quantity: Int }
'
# Import from an introspection JSON result (both envelope forms are accepted)
curl -s -X PUT "http://localhost:1080/mockserver/graphql" \
  -H "Content-Type: application/json" \
  -d '{ "data": { "__schema": { ... } } }'

The optional ?path= query parameter overrides the default /graphql request path the generated expectations match:

curl -s -X PUT "http://localhost:1080/mockserver/graphql?path=/api/graphql" \
  -H "Content-Type: application/graphql" \
  --data-raw 'type Query { ping: String }'

On success, the endpoint returns 201 Created with a JSON array of the generated expectations. On a schema parse error it returns 400 Bad Request with a plain-text error message.

 

Schema-Driven Response Synthesis

When a matched GraphQL expectation has a schema attached — either via schema import or a schema field on a GRAPHQL body — MockServer synthesizes a schema-valid response for the actual query at request time, rather than returning a fixed stub. Only the fields the client requested appear in the response (the selection set is honoured).

Synthesis rules follow GraphQL execution semantics:

  • Scalar placeholdersString"string", Int0, Float0.0, Booleantrue, ID"id"
  • Enum types — the first declared value
  • List types — a single-element array containing the synthesized element
  • Object types — recurse into the sub-selection set
  • Inline fragments and named fragment spreads — flattened into the selection set
  • Non-null wrappers — unwrapped transparently

The synthesized response is wrapped in a {"data": {...}} envelope. An explicit response body on the expectation always takes precedence — schema synthesis only fires when the response body is absent.

Example: given the schema above, a client query of { user(id: "1") { name email } } produces:

{
  "data": {
    "user": {
      "name": "string",
      "email": "string"
    }
  }
}
 

GraphQL Body Matcher in Expectations

To match specific GraphQL operations, set the request body type to GRAPHQL in an expectation. The body matcher supports three match modes:

Match mode selectionSetMatchType Description
Normalised string (default) NORMALISED_STRING Whitespace-normalised string comparison of the full query text. Use this when you want to match a known, fixed query string exactly.
Exact AST AST_EXACT The operation type, name, and top-level field set must match exactly.
Subset AST AST_SUBSET The expected fields must be a subset of the actual query's top-level fields. Useful when matching "any query that includes field X" regardless of what other fields are requested.

Additional body matcher fields:

Field Type Description
query string The GraphQL query/mutation/subscription string to match against. For NORMALISED_STRING mode, whitespace is normalised before comparison.
operationName string Optional exact operation name to match (plain string or regex). Only applies to named operations.
variablesSchema string Optional JSON Schema string. When set, the variables in the GraphQL request body are validated against this schema as an additional match condition.
schema string GraphQL SDL or introspection JSON to attach to this expectation. When present and the response body is absent, MockServer synthesizes a schema-valid response for the matched query.
 

Explicit Expectation Examples

Match a specific query string and return an explicit response

curl -s -X PUT http://localhost:1080/mockserver/expectation \
  -H "Content-Type: application/json" \
  -d '{
    "httpRequest": {
      "method": "POST",
      "path": "/graphql",
      "body": {
        "type": "GRAPHQL",
        "query": "query GetUser($id: ID!) { user(id: $id) { name email } }"
      }
    },
    "httpResponse": {
      "statusCode": 200,
      "headers": { "Content-Type": ["application/json"] },
      "body": "{\"data\":{\"user\":{\"name\":\"Alice\",\"email\":\"alice@example.com\"}}}"
    }
  }'

Match any query that includes a specific field (subset AST)

curl -s -X PUT http://localhost:1080/mockserver/expectation \
  -H "Content-Type: application/json" \
  -d '{
    "httpRequest": {
      "method": "POST",
      "path": "/graphql",
      "body": {
        "type": "GRAPHQL",
        "query": "query { user { email } }",
        "selectionSetMatchType": "AST_SUBSET"
      }
    },
    "httpResponse": {
      "statusCode": 200,
      "headers": { "Content-Type": ["application/json"] },
      "body": "{\"data\":{\"user\":{\"id\":\"1\",\"name\":\"Alice\",\"email\":\"alice@example.com\"}}}"
    }
  }'

Match by operation name and validate variables with JSON Schema

curl -s -X PUT http://localhost:1080/mockserver/expectation \
  -H "Content-Type: application/json" \
  -d '{
    "httpRequest": {
      "method": "POST",
      "path": "/graphql",
      "body": {
        "type": "GRAPHQL",
        "query": "mutation CreateOrder($input: OrderInput!) { createOrder(input: $input) { id status } }",
        "operationName": "CreateOrder",
        "variablesSchema": "{\"type\":\"object\",\"properties\":{\"input\":{\"type\":\"object\",\"required\":[\"productId\",\"quantity\"]}},\"required\":[\"input\"]}"
      }
    },
    "httpResponse": {
      "statusCode": 200,
      "headers": { "Content-Type": ["application/json"] },
      "body": "{\"data\":{\"createOrder\":{\"id\":\"order-42\",\"status\":\"PENDING\"}}}"
    }
  }'

Schema-attached expectation (response synthesized from query)

Provide a schema on the body and omit the response body — MockServer synthesizes a schema-valid response for whatever fields the client requests:

curl -s -X PUT http://localhost:1080/mockserver/expectation \
  -H "Content-Type: application/json" \
  -d '{
    "httpRequest": {
      "method": "POST",
      "path": "/graphql",
      "body": {
        "type": "GRAPHQL",
        "query": "query { }",
        "selectionSetMatchType": "AST_SUBSET",
        "schema": "type Query { user(id: ID!): User } type User { id: ID! name: String email: String }"
      }
    },
    "httpResponse": {}
  }'
 

GraphQL Error Injection (Chaos)

GraphQL APIs return HTTP 200 even for errors — error details live in an errors array in the response body. Standard HTTP error injection (which changes the status code) does not reproduce this pattern. Use the graphqlErrors chaos profile field to inject a spec-compliant GraphQL error envelope.

See GraphQL Error Injection in the Chaos Testing page for the full reference including graphqlErrorMessage, graphqlErrorCode, graphqlNullifyData, and how to apply it via service-scoped chaos (PUT /mockserver/serviceChaos).

 

GraphQL Subscriptions

MockServer generates a subscription expectation from the schema when a Subscription root type is present. Subscription operations are matched using the same GRAPHQL body type. The transport (WebSocket or SSE) depends on how the client connects; MockServer handles both via its WebSocket response action (httpWebSocketResponse). See the Creating Expectations page for WebSocket response details.

 

Related Pages

  • OpenAPI Import — import an OpenAPI 3.x spec to generate REST mock expectations; the same schema-import pattern as GraphQL
  • gRPC Mocking — import a proto descriptor to generate gRPC mock expectations with response synthesis
  • AsyncAPI Messaging — mock message-broker interactions from an AsyncAPI spec
  • GraphQL Error Injection — inject spec-compliant GraphQL error envelopes via chaos profiles
  • Creating Expectations — full reference for the expectation model, body matchers, and response actions