Skip to main content

JSON in GraphQL

Learning Focus

GraphQL uses JSON for both requests and responses, but follows its own conventions — single endpoint, typed query language, and structured error handling.

GraphQL Request Structure

All GraphQL requests are POST to a single endpoint (/graphql) with a JSON body:

{
"query": "query { user(id: 1) { name email } }",
"variables": { "id": 1 },
"operationName": "GetUser"
}
FieldRequiredPurpose
queryThe GraphQL query or mutation string
variablesInput variables for the query
operationNameName to identify the operation

GraphQL Response Structure

GraphQL responses always return 200 OK (even for errors):

{
"data": {
"user": {
"name": "Alice",
"email": "alice@example.com"
}
},
"errors": null
}

Response with Partial Data and Errors

{
"data": {
"user": { "name": "Alice", "email": null }
},
"errors": [
{
"message": "Could not resolve email field",
"locations": [{ "line": 1, "column": 25 }],
"path": ["user", "email"]
}
]
}

Mutation Request

{
"query": "mutation CreateUser($input: UserInput!) { createUser(input: $input) { id name } }",
"variables": {
"input": {
"name": "Bob",
"email": "bob@example.com"
}
}
}

REST vs GraphQL JSON

AspectRESTGraphQL
EndpointMultiple (/users, /products)Single (/graphql)
Request methodGET, POST, PATCH, DELETEAlways POST
Response shapeFixed by serverClient-defined
Over/under-fetchingCommonEliminated by design
Error status codes4xx / 5xxAlways 200 (errors in body)
Content-Typeapplication/jsonapplication/json

Concept Map

Concept Flow

GraphQL Client → POST /graphql + JSON body → GraphQL Server
GraphQL Server → 200 OK + JSON body → Client
├── data: requested fields only
└── errors: field-level error array (if any)

Common Pitfalls

PitfallConsequencePrevention
Checking HTTP status for GraphQL errorsAlways 200 — misses field errorsAlways check response.errors array
Sending GET for mutationsMutations must be POSTAlways POST GraphQL requests
Large nested queriesDeep JSON responses are slowUse query depth limiting and pagination

What's Next