HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
5 Topics
Chapter•95 Minutes

GraphQL Fundamentals

Understand why GraphQL was created, how it differs from REST, how a GraphQL request flows through a system, and the core terminology you will use throughout the course.

What Is GraphQL?

Level:BeginnerConcept:Foundation

GraphQL is a query language for APIs and a runtime for executing those queries against a type system that you define for your data.

Unlike a traditional REST API, where the server exposes multiple endpoints such as /users, /users/42, and /users/42/posts, GraphQL generally exposes a single endpoint through which the client describes the data it needs.

The important idea is that the client does not simply ask the server for a resource. It asks for a specific shape of data.

For example, a client might request:

query {
  user(id: "42") {
    id
    name
    email
  }
}

The response follows the structure requested by the client:

{
  "data": {
    "user": {
      "id": "42",
      "name": "Suriya",
      "email": "suriya@example.com"
    }
  }
}

GraphQL itself does not require MongoDB, Node.js, React, Apollo, or any particular programming language. It defines a specification for describing an API schema, querying that schema, validating operations, and executing them.

A GraphQL server typically has three important responsibilities:

  1. Define the schema that describes available data and operations.
  2. Validate incoming operations against that schema.
  3. Execute valid operations using resolver functions.

This separation between the API contract and the underlying data sources is one of GraphQL's most important architectural characteristics.

Specifications & Requirements
  • Type:API query language and runtime
  • :Client specifies the required data shape
  • :/graphql
Basic GraphQL Request Flow
A Minimal GraphQL Query
query GetUser {
  user(id: "42") {
    id
    name
    email
  }
}
💡 The operation is named GetUser. The user field represents an operation exposed by the GraphQL schema. The id argument identifies the requested user. Inside the selection set, the client explicitly chooses id, name, and email. GraphQL validates this entire structure before execution. If email is not a field on the User type, the operation is rejected instead of silently returning an unexpected response.
Key Takeaways
  • GraphQL is a query language for APIs and a runtime for executing queries against a schema.
  • Clients describe the exact fields they need.
  • The schema acts as the contract between clients and the server.
  • GraphQL is not tied to a specific database or programming language.
Knowledge Check

What is the primary characteristic that distinguishes a GraphQL query from a typical REST resource request?

Why Was GraphQL Created?

GraphQL was designed to solve problems that became increasingly visible as client applications became more sophisticated.

A traditional REST API often models server resources through endpoints. That model works well for many applications, but complex user interfaces can require data from many related resources.

Imagine a social application displaying a user's profile, recent posts, author information, comments, and reactions. A REST client might need several requests:

GET /users/42
GET /users/42/posts
GET /posts/101/comments
GET /posts/101/reactions

This can create several problems.

Over-fetching

An endpoint may return fields that the client does not need. A mobile application might only require a user's name and avatar, while /users/42 returns dozens of additional fields.

Under-fetching

A response may not contain enough information to render the screen, forcing the client to make additional requests.

Endpoint proliferation

As application requirements grow, teams may add increasingly specialized endpoints for different clients and screens.

Client-specific requirements

A web application, mobile application, admin application, and smart TV application may need different representations of the same underlying data.

GraphQL addresses these issues by allowing clients to select the fields they need from a typed graph of related data.

However, GraphQL is not automatically better than REST in every situation. REST remains an excellent choice for many APIs. The correct choice depends on requirements such as caching strategy, operational complexity, team experience, API consumers, and data access patterns.

Common API Problems
Over-fetching: Receiving fields that are not required
A large REST response may contain much more information than a particular screen needs.
Under-fetching: Needing multiple requests
The first response may not contain all data needed to render a feature.
Endpoint growth: Increasing number of specialized endpoints
Different clients or screens can lead to increasingly specific REST endpoints.
Key Takeaways
  • GraphQL was created to improve flexibility for data-driven clients.
  • Over-fetching means receiving unnecessary fields.
  • Under-fetching can force clients to make additional requests.
  • GraphQL solves specific API design problems but is not universally superior to REST.
Knowledge Check

A mobile screen needs only a user's name and profile image, but the REST endpoint returns 30 additional fields. What problem does this demonstrate?

GraphQL vs REST

GraphQL and REST can both be used to build production APIs, but they model API interaction differently.

In REST, the API is usually organized around resources and HTTP endpoints. In GraphQL, the API is organized around a typed schema and operations.

A REST API might expose:

GET    /users/42
GET    /users/42/posts
POST   /users
PATCH  /users/42
DELETE /users/42

A GraphQL API may expose a single endpoint such as /graphql, with operations represented in the schema:

query {
  user(id: "42") {
    name
    posts {
      title
    }
  }
}

GraphQL's single endpoint does not mean that GraphQL has only one operation. The schema can expose many query fields and mutation fields through that endpoint.

REST strengths

REST integrates naturally with HTTP semantics. HTTP caching, status codes, proxies, CDNs, and resource-oriented tooling are well understood.

GraphQL strengths

GraphQL provides a strongly typed schema, client-controlled selection sets, nested data fetching, introspection, and a unified API contract.

Important distinction

GraphQL does not eliminate HTTP. GraphQL is frequently transported over HTTP. It changes how API operations and response shapes are modeled rather than replacing the network itself.

REST and GraphQL
API structure: REST: resources/endpoints; GraphQL: schema/operations
REST commonly maps resources to URLs, while GraphQL exposes fields and operations through a schema.
Response shape: REST: server-defined representation; GraphQL: client selection
GraphQL lets the client select fields from the schema.
Transport: REST commonly uses HTTP; GraphQL commonly uses HTTP
GraphQL does not require a completely different network transport.
Do not think of GraphQL as REST with one endpoint

The most important difference is the API model. GraphQL exposes a typed graph of operations and fields rather than simply moving REST resources behind a single URL.

Key Takeaways
  • REST is resource-oriented while GraphQL is schema and operation-oriented.
  • GraphQL commonly uses one HTTP endpoint but can expose many operations.
  • GraphQL still commonly runs over HTTP.
  • Both approaches can be appropriate for production systems.
Knowledge Check

Which statement most accurately describes GraphQL compared with REST?

Core GraphQL Terminology

Foundation:Core vocabulary

Before writing a serious GraphQL application, you need to understand the vocabulary used by the specification and ecosystem.

Schema

The schema defines what clients are allowed to query and what data types and operations are available.

Type

A type describes the shape of data. Examples include User, Product, Order, and Post.

Field

A field is a property or operation exposed by a type.

type User {
  id: ID!
  name: String!
  email: String!
}

Here id, name, and email are fields.

Query

A query is a read operation. It retrieves data without being intended to modify server state.

Mutation

A mutation represents an operation that changes server-side state, such as creating, updating, or deleting data.

Subscription

A subscription represents a long-lived operation used for receiving events or updates, commonly through a real-time transport.

Resolver

A resolver is a function responsible for obtaining or computing the value of a field.

Selection set

The fields enclosed inside { } after an object field form a selection set.

user {
  id
  name
}

Argument

An argument supplies input to a field.

user(id: "42")

Scalar

A scalar represents a leaf value such as String, Int, Float, Boolean, or ID.

These concepts build on each other. A schema defines types, types contain fields, fields can accept arguments, clients select fields in operations, and resolvers provide the values during execution.

GraphQL Vocabulary
Schema: Defines the API contract
It describes available types, fields, arguments, and operations.
Resolver: Produces field values
Resolvers connect schema fields to application logic and data sources.
Query: Read operation
Queries retrieve data.
Mutation: State-changing operation
Mutations are conventionally used for writes.
Subscription: Real-time operation
Subscriptions allow clients to receive ongoing event updates.
Key Takeaways
  • The schema is the central contract of a GraphQL API.
  • Types describe data structures.
  • Fields belong to types.
  • Resolvers provide field values during execution.
  • Queries, mutations, and subscriptions represent different operation categories.
Knowledge Check

What is a resolver primarily responsible for?

How a GraphQL Request Works

A GraphQL request goes through several conceptual stages before the client receives a response.

Suppose the client sends:

query GetProduct($id: ID!) {
  product(id: $id) {
    id
    name
    price
  }
}

with variables:

{
  "id": "p100"
}

The server conceptually performs the following steps.

1. Receive the operation

The server receives the GraphQL document and any variables.

2. Parse

The GraphQL document is converted into an internal representation called an AST, or Abstract Syntax Tree.

3. Validate

The operation is checked against the schema. The server verifies that fields exist, arguments have valid types, required values are present, and selections are valid.

4. Execute

If validation succeeds, GraphQL executes the operation. Resolver functions are invoked to obtain the requested values.

5. Complete values

GraphQL processes returned values according to the field types. This includes handling nested objects, lists, scalar serialization, and nullability rules.

6. Return the response

The result normally contains a data property and may also contain an errors property.

For example:

{
  "data": {
    "product": {
      "id": "p100",
      "name": "Keyboard",
      "price": 2499
    }
  }
}

Understanding this lifecycle becomes extremely important later when debugging validation errors, resolver failures, null propagation, authorization behavior, and performance issues.

GraphQL Request Lifecycle
Key Takeaways
  • GraphQL parses the incoming document before execution.
  • Validation occurs against the schema.
  • Resolvers participate during execution.
  • The response can contain both data and errors.
  • Understanding the lifecycle is essential for debugging.
Knowledge Check

What happens if a GraphQL query requests a field that does not exist on the corresponding schema type?