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"
}
| Field | Required | Purpose |
|---|---|---|
query | ✓ | The GraphQL query or mutation string |
variables | ✗ | Input variables for the query |
operationName | ✗ | Name 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
| Aspect | REST | GraphQL |
|---|---|---|
| Endpoint | Multiple (/users, /products) | Single (/graphql) |
| Request method | GET, POST, PATCH, DELETE | Always POST |
| Response shape | Fixed by server | Client-defined |
| Over/under-fetching | Common | Eliminated by design |
| Error status codes | 4xx / 5xx | Always 200 (errors in body) |
| Content-Type | application/json | application/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
| Pitfall | Consequence | Prevention |
|---|---|---|
| Checking HTTP status for GraphQL errors | Always 200 — misses field errors | Always check response.errors array |
| Sending GET for mutations | Mutations must be POST | Always POST GraphQL requests |
| Large nested queries | Deep JSON responses are slow | Use query depth limiting and pagination |
What's Next
- Previous: JSON and REST APIs — Review REST conventions.
- Next: JSON in Databases — Native JSON storage in SQL.
- Section Overview — Return to the Web APIs module index.