GraphQL Overview

GraphQL is a strongly typed query language and runtime designed to enable clients to request exactly the data they need from an API. It was originally developed by Facebook and is now maintained by the GraphQL Foundation.

Unlike traditional REST APIs, GraphQL exposes a single endpoint and allows clients to define the structure of the response, reducing over-fetching and under-fetching of data.

Key Characteristics

  • Declarative data fetching

  • Strongly typed schema

  • Hierarchical queries

  • Single endpoint architecture

  • Real-time capabilities via subscriptions


Core Concepts

Schema

A schema defines the structure of the API, including types, queries, mutations, and subscriptions.

type Query {
  post(id: ID!): Post
  posts: [Post]
}

type Post {
  id: ID!
  title: String!
  content: String
  author: User
}

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

Notes:

  • ID! indicates a non-nullable field.

  • Square brackets ([]) denote lists.

  • Types define relationships between entities.


Queries

Queries are used to fetch data.

query GetPost {
  post(id: "1") {
    title
    content
    author {
      name
    }
  }
}

Notes:

  • Clients specify required fields explicitly.

  • Nested queries allow fetching related data in one request.

  • Reduces the need for multiple API calls.


Mutations

Mutations are used to modify data.

mutation CreatePost {
  createPost(input: {
    title: "New Post",
    content: "GraphQL is powerful"
  }) {
    post {
      id
      title
    }
  }
}

Notes:

  • Mutations follow a structured input pattern.

  • Typically used for create, update, delete operations.

  • Can return modified objects.


Subscriptions

Subscriptions enable real-time updates.

subscription OnPostCreated {
  postCreated {
    id
    title
  }
}

Notes:

  • Uses WebSockets or similar protocols.

  • Ideal for live feeds, notifications, and chat systems.


GraphQL vs REST

Architectural Differences

FeatureGraphQLREST
EndpointsSingle endpointMultiple endpoints
Data FetchingClient-definedServer-defined
Over-fetchingAvoidedCommon
VersioningNot requiredOften required
Response StructureMatches queryFixed structure

REST Example

GET /posts/1
GET /posts/1/author

GraphQL Equivalent

query {
  post(id: "1") {
    title
    author {
      name
    }
  }
}

Notes:

  • GraphQL reduces multiple round trips.

  • REST is simpler and better suited for caching via HTTP.

  • GraphQL introduces complexity in schema design.