Course contentsShow
← System Design
Lesson 1912 of 1,91945. API Design and VersioningFree lesson

GraphQL Schema and Resolvers

Defining schemas with types, queries, mutations, and implementing resolvers that fetch data from underlying sources.

GraphQL Schema and Resolvers

What You'll Learn

You'll learn how GraphQL schemas define your API's structure with types, queries, and mutations, while resolvers connect these definitions to actual data sources.

The Core Idea

Think of a GraphQL schema as a contract or blueprint—it declares what data clients can request and how that data is shaped. Resolvers are the implementation functions that fulfill that contract by actually fetching or manipulating data.

Schema: Defining the API Surface

The schema uses the GraphQL Schema Definition Language (SDL) to declare:

  • Types: Object structures with fields (e.g., User, Post)
  • Queries: Read operations clients can perform (e.g., getUser(id: ID!))
  • Mutations: Write operations for creating or modifying data (e.g., createPost(title: String!))

Example schema snippet:

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

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

type Mutation {
  updateUser(id: ID!, name: String): User
}

This defines a User type and operations to fetch or update users—but no actual data logic yet.

Resolvers: The Data Fetching Layer

Resolvers are functions mapped to each field in your schema. When a client requests user(id: "123"), GraphQL invokes the corresponding resolver function, which might query a database, call a microservice, or aggregate from multiple sources.

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

Each resolver receives arguments, context (like auth info), and can return data synchronously or via promises.

Key Takeaway:
The schema is your API's type-safe contract; resolvers are the runtime functions that fetch data from databases, services, or caches to fulfill that contract, separating interface definition from implementation details.