GraphQL is a query language for APIs, developed by Facebook in 2015 and released as an open standard. Unlike REST, GraphQL provides a single access point and lets the client specify exactly which data it needs.
Basic GraphQL syntax
Query — retrieving data
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
posts {
title
createdAt
}
}
}Mutation — modifying data
mutation CreatePost($input: PostInput!) {
createPost(input: $input) {
id
title
author {
name
}
}
}Fragments — reusable blocks
fragment UserFields on User {
id
name
avatarUrl
}
query {
me { ...UserFields }
user(id: "1") { ...UserFields }
}GraphQL vs. REST
| Criterion | REST | GraphQL |
|---|---|---|
| Endpoints | Many (/users, /posts, ...) | One (/graphql) |
| Over-fetching | Possible | No — the client specifies the fields |
| Under-fetching | Requires N+1 requests | One request for nested data |
| Versioning | /v1, /v2 | The schema evolves |
| Caching | HTTP caching works | Requires configuration (Apollo, Relay) |
| Introspection | No (or OpenAPI separately) | Built into the specification |
Why format GraphQL queries
Readability: a minified query on a single line is difficult to debug. Indentation makes field nesting visible.
Minification: for production requests, extra spaces and line breaks are removed to reduce the request body size.
Minification example:
# Исходный запрос (65 символов с пробелами)
query { user(id: "1") { name email } }
# Минифицированный (36 символов)
query{user(id:"1"){name email}}Type system and schema
GraphQL is a strongly typed language. The schema defines the data structure:
type User {
id: ID!
name: String!
email: String
age: Int
posts: [Post!]!
}
type Query {
user(id: ID!): User
users: [User!]!
}
type Mutation {
createUser(name: String!, email: String!): User!
}! means a non-nullable field. [Post!]! is a non-nullable list of non-nullable elements.
To work with GraphQL JSON responses, use the JSON formatter and JSONPath to extract data.
Tool on reChecker
The GraphQL formatter on reChecker formats queries with proper indentation for readability or minifies them for sending. It highlights syntax errors before execution.