Testing GraphQL APIs with Karate DSL
GraphQL APIs are just HTTP endpoints that accept POST requests with JSON bodies. Karate handles them the same way it handles any REST API — but there are GraphQL-specific patterns worth knowing. This guide covers testing GraphQL with Karate from simple queries through subscriptions and performance testing.
GraphQL Basics for Karate
Every GraphQL request is a POST to a single endpoint (usually /graphql) with a JSON body:
{
"query": "{ users { id name email } }",
"variables": {},
"operationName": "GetUsers"
}In Karate:
Feature: GraphQL API
Background:
* url 'https://api.example.com/graphql'
* header Content-Type = 'application/json'
Scenario: Get users query
And request
"""
{
"query": "{ users { id name email } }"
}
"""
When method POST
Then status 200
And match response.data.users == '#[]'
And match response.errors == '#notpresent'GraphQL always returns HTTP 200, even for errors. Check response.errors explicitly.
Queries
Simple Query
Scenario: Query a single user
And request
"""
{
"query": "query GetUser($id: ID!) { user(id: $id) { id name email createdAt } }",
"variables": { "id": "1" }
}
"""
When method POST
Then status 200
And match response.data.user.id == '1'
And match response.data.user.name == '#string'
And match response.errors == '#notpresent'Multi-line Queries with Text Block
For readable complex queries, use Karate's multi-line text block with a separate variable:
Scenario: Query with nested fields
* def query =
"""
query GetUserWithOrders($userId: ID!) {
user(id: $userId) {
id
name
email
orders {
id
status
total
items {
productId
quantity
price
}
}
}
}
"""
And request { query: '#(query)', variables: { userId: '42' } }
When method POST
Then status 200
And match response.data.user.orders == '#[]'
And match response.data.user.orders[0].items == '#[]'Reusable Query Files
For large projects, keep queries in separate .graphql files:
# src/test/java/queries/get-user.graphql
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
role
createdAt
}
}Load in Karate:
Background:
* def getUserQuery = read('classpath:queries/get-user.graphql')
Scenario: Get user
And request { query: '#(getUserQuery)', variables: { id: '1' } }
When method POST
Then status 200
And match response.data.user.name == '#string'Mutations
Feature: GraphQL Mutations
Background:
* url 'https://api.example.com/graphql'
* header Content-Type = 'application/json'
* header Authorization = 'Bearer admin-token'
Scenario: Create a user mutation
* def createUserMutation =
"""
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
createdAt
}
}
"""
And request
"""
{
"query": "#(createUserMutation)",
"variables": {
"input": {
"name": "Alice Johnson",
"email": "alice@example.com",
"role": "editor"
}
}
}
"""
When method POST
Then status 200
And match response.errors == '#notpresent'
And match response.data.createUser.id == '#string'
And match response.data.createUser.name == 'Alice Johnson'
* def userId = response.data.createUser.idUpdate Mutation
Scenario: Update a user
* def updateMutation =
"""
mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {
updateUser(id: $id, input: $input) {
id
name
email
}
}
"""
And request
"""
{
"query": "#(updateMutation)",
"variables": {
"id": "42",
"input": { "name": "Alice Smith" }
}
}
"""
When method POST
Then status 200
And match response.errors == '#notpresent'
And match response.data.updateUser.name == 'Alice Smith'Delete Mutation
Scenario: Delete a user
* def deleteMutation = 'mutation { deleteUser(id: "42") { success } }'
And request { query: '#(deleteMutation)' }
When method POST
Then status 200
And match response.data.deleteUser.success == trueVariables
Using variables (rather than string interpolation) is the correct approach for GraphQL:
Scenario: Search users with variables
* def searchQuery = 'query Search($term: String!, $limit: Int) { searchUsers(term: $term, limit: $limit) { id name } }'
* def variables = { term: 'alice', limit: 10 }
And request { query: '#(searchQuery)', variables: '#(variables)' }
When method POST
Then status 200
And match response.data.searchUsers == '#[]'Never build queries with string concatenation. It's harder to read and bypasses GraphQL's variable type checking.
Error Handling
GraphQL errors don't change the HTTP status code. Always check response.errors:
Scenario: Query nonexistent user returns GraphQL error
And request
"""
{
"query": "query { user(id: \"99999\") { id name } }"
}
"""
When method POST
Then status 200
And match response.data.user == null
And match response.errors == '#[]'
And match response.errors[0].message == '#string'
And match response.errors[0].locations == '#present'Partial Data with Errors
GraphQL can return both data and errors in the same response:
Scenario: Partial response with some errors
And request
"""
{
"query": "{ user(id: \"1\") { id name } restrictedData { secret } }"
}
"""
When method POST
Then status 200
# Some data returned
And match response.data.user.id == '1'
# But restricted field errored
And match response.errors[0].path contains 'restrictedData'
And match response.errors[0].extensions.code == 'UNAUTHORIZED'Validation Errors
Scenario: Mutation with invalid input
And request
"""
{
"query": "mutation { createUser(input: { name: \"\", email: \"not-an-email\" }) { id } }"
}
"""
When method POST
Then status 200
And match response.data == null
And match response.errors == '#[]'
And match response.errors[0].extensions.code == 'VALIDATION_ERROR'Authentication
Bearer Token Auth
Background:
* url 'https://api.example.com/graphql'
* def loginResult = call read('classpath:features/auth/login.feature')
* def authHeader = 'Bearer ' + loginResult.token
* header Authorization = authHeader
* header Content-Type = 'application/json'API Key Auth
Background:
* url 'https://api.example.com/graphql'
* header X-API-Key = 'your-api-key'
* header Content-Type = 'application/json'Introspection Tests
Introspection lets you verify the schema itself:
Scenario: Schema introspection returns type list
And request
"""
{
"query": "{ __schema { types { name kind } } }"
}
"""
When method POST
Then status 200
And match response.data.__schema.types == '#[]'
* def typeNames = $response.data.__schema.types[*].name
And assert typeNames.contains('User')
And assert typeNames.contains('Query')
And assert typeNames.contains('Mutation')Verify Field Exists in Schema
Scenario: User type has expected fields
And request
"""
{
"query": "{ __type(name: \"User\") { fields { name type { name kind } } } }"
}
"""
When method POST
Then status 200
* def fieldNames = $response.data.__type.fields[*].name
And assert fieldNames.contains('id')
And assert fieldNames.contains('name')
And assert fieldNames.contains('email')Introspection tests are useful as contract tests — they fail if someone removes a field or type that your clients depend on.
Batched Queries
Some GraphQL APIs support query batching:
Scenario: Batch multiple queries
And request
"""
[
{ "query": "{ user(id: \"1\") { id name } }", "operationName": "GetUser1" },
{ "query": "{ user(id: \"2\") { id name } }", "operationName": "GetUser2" }
]
"""
When method POST
Then status 200
And match response == '#[]'
And match response[0].data.user.id == '1'
And match response[1].data.user.id == '2'Performance Testing GraphQL
Karate integrates with Gatling for load testing. You can load-test specific queries:
class GraphQLSimulation extends Simulation {
setUp(
scenario("GraphQL user query load test")
.exec(karateFeature("classpath:features/graphql/users-query.feature"))
.inject(
rampUsers(50).during(30),
constantUsersPerSec(10).during(60)
)
).protocols(karateProtocol(
uri("/graphql").method("POST").tag("users-query")
));
}Track response times per operation name in the Gatling report.
Common Patterns
Chaining Create → Query → Cleanup
Scenario: Create user, query them, then delete
# Create
* def createResult = call read('create-user.feature') { name: 'Test User', email: 'test@example.com' }
* def userId = createResult.userId
# Query
Given url 'https://api.example.com/graphql'
And request
"""
{
"query": "query GetUser($id: ID!) { user(id: $id) { id name email } }",
"variables": { "id": "#(userId)" }
}
"""
When method POST
Then status 200
And match response.data.user.name == 'Test User'
# Cleanup
And request
"""
{
"query": "mutation DeleteUser($id: ID!) { deleteUser(id: $id) { success } }",
"variables": { "id": "#(userId)" }
}
"""
When method POST
Then status 200
And match response.data.deleteUser.success == trueData-Driven Queries
Scenario Outline: Query users with different filters
And request
"""
{
"query": "query FilterUsers($role: String) { users(role: $role) { id role } }",
"variables": { "role": "<role>" }
}
"""
When method POST
Then status 200
And match each response.data.users == { id: '#string', role: '<role>' }
Examples:
| role |
| admin |
| editor |
| viewer |Karate Configuration for GraphQL
If all tests hit the same GraphQL endpoint, centralize in karate-config.js:
function fn() {
var config = {
graphqlUrl: 'https://api.example.com/graphql',
graphqlHeaders: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
if (karate.env == 'staging') {
config.graphqlUrl = 'https://staging.api.example.com/graphql';
}
return config;
}Then in feature files:
Background:
* url graphqlUrl
* headers graphqlHeadersGraphQL testing with Karate is straightforward once you understand that every operation is a POST with a JSON body. The power is in Karate's matching — you can assert deeply nested responses, check for absent error fields, and verify partial data responses with minimal syntax.