GraphQL Communication
Last updated
Last updated
GraphQL is a flexible query layer between the client and backend, allowing precise data retrieval. Its schema-driven structure ensures strong typing and easy query formation but requires careful design to avoid vulnerabilities like DoS from poorly written resolvers or two-way links.
When a client communicates with a GraphQL server (e.g., to fetch usernames or emails), the client sends a GraphQL query via the HTTP POST method. Though data retrieval typically uses the GET method in REST, GraphQL deviates here.
Query Parser Validates the query’s format and ensures it matches the GraphQL schema. Queries must comply with the application schema to be accepted.
Schema The schema defines what data is available for querying. For example:
Object Types: These are the building blocks of GraphQL schemas, representing data entities (e.g., User
, Location
).
Fields: Attributes specific to objects, such as username
or latitude
.
Resolver Functions These handle data retrieval, e.g., fetching user details from a database.
GraphQL schemas allow linking objects using edges. For example, a User
can reference a Location
:
This enables querying User
data alongside their Location
. However, the reverse isn’t possible unless explicitly defined in the schema.
Two-way links (e.g., allowing both User
and Location
to reference each other) should be used cautiously as they can introduce vulnerabilities like denial-of-service (DoS) attacks.
GraphQL supports three main operation types:
Queries (read-only operations):
Retrieves usernames and emails of all users.
Mutations (data manipulation):
Adds a new user to the database.
Subscriptions (real-time updates):
Subscriptions are used for real-time communications between clients and GraphQL servers. They allow a GraphQL server to push data to the client when different events occur. Subscriptions typically are used in conjunction with transport protocols such as WebSocket.
Each query begins with a root type (e.g., Query
, Mutation
).
Here’s a schema that allows querying users:
A corresponding query:
Notice that, while field names (like
users
) are lowercase, object names (likeUser
) begin with an uppercase letter. This is the most common naming convention in GraphQL schemas.
Parsing & Validation: The server uses a query parser to validate and convert the query into an abstract syntax tree (AST). This ensures compliance with the schema.
Resolver Execution: Resolvers fetch data (e.g., from a database, file, or another API) and populate the query response.
Resolvers can handle complex tasks, such as making REST API calls, interacting with caching layers, or performing file lookups.