Dung (Donny) Nguyen

Senior Software Engineer

Key Components of GraphQL

GraphQL revolves around a few core components that enable the client-server interaction. Here are the key components:


1. Query

Example of a Query:

query {
  user(id: 1) {
    id
    name
    email
  }
}

Response:

{
  "data": {
    "user": {
      "id": 1,
      "name": "Alice",
      "email": "alice@example.com"
    }
  }
}

2. Mutation

Example of a Mutation:

mutation {
  createUser(name: "Bob", email: "bob@example.com") {
    id
    name
    email
  }
}

Response:

{
  "data": {
    "createUser": {
      "id": 2,
      "name": "Bob",
      "email": "bob@example.com"
    }
  }
}

3. Subscription

Example of a Subscription:

subscription {
  newMessage {
    id
    content
    sender
  }
}

4. Schema

Example of a Schema:

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

type Query {
  user(id: ID!): User
}

type Mutation {
  createUser(name: String!, email: String!): User
}

type Subscription {
  newUser: User
}

5. Resolver

Resolvers have the following signature:

(parent, args, context, info) => { ... }

Example Resolver for user Query:

const resolvers = {
  Query: {
    user: (parent, args, context) => {
      return context.db.getUserById(args.id);
    },
  },
  Mutation: {
    createUser: (parent, args, context) => {
      return context.db.createUser(args.name, args.email);
    },
  },
};

Summary Table of Components

Component Description
Query Fetches data from the server. Similar to REST’s GET request.
Mutation Modifies data (create, update, delete). Similar to POST/PUT/DELETE requests.
Subscription Provides real-time updates by listening to server-side events.
Schema The blueprint that defines the types, queries, mutations, and subscriptions.
Resolver Functions that handle fetching or modifying data for each field in the schema.

Together, these components enable GraphQL to provide a flexible, predictable, and efficient way of interacting with APIs.