Skip to content

GraphQL Schema

The schema is the backbone of any GraphQL API. It defines the structure of data available on the server: types, fields, relationships, and operations (queries, mutations, subscriptions).

A well-designed schema acts as a contract between the client and the server.


What Is a Schema?

In GraphQL, a schema defines:

  • Object types (e.g., User, Post)
  • Fields each type exposes
  • How clients can interact with the data (via queries/mutations)
  • Entry points to the graph (Query, Mutation, Subscription)

Basic Schema Structure

schema {
  query: Query
  mutation: Mutation
}

The schema block identifies the entry points.


Example Types

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

type Mutation {
  createPost(title: String!, content: String!): Post
}

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

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

Scalars and Custom Types

Built-in Scalars

  • Int
  • Float
  • String
  • Boolean
  • ID

Custom Scalars

You can define your own scalars for things like Date, JSON, etc.

scalar Date

type Event {
  id: ID!
  name: String!
  date: Date!
}

Custom scalars require custom serialization logic on the server.


Non-Null and Lists

  • String → nullable string
  • String! → non-nullable string
  • [String] → nullable list of strings
  • [String!]! → non-null list of non-null strings

Relationships

Schemas naturally model relationships using nested types.

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

Schema Design Tips

  • ✅ Think in terms of what the client needs, not your DB structure.
  • ✅ Keep your schema intuitive and consistent.
  • ✅ Prefer specific types over JSON blobs.
  • ✅ Use meaningful type and field names.
  • ✅ Model real-world entities and relationships.

SDL vs Code-First

You can define schemas in two ways:

Approach Description Example Tools
SDL (Schema Definition Language) Write schema in .graphql or .gql files Apollo Server, Yoga
Code-First Use code (usually decorators or functions) TypeGraphQL, Nexus, Pothos

Tools


Summary

  • The schema defines types, fields, and operations.
  • It is the foundation of every GraphQL server.
  • A good schema leads to better developer experience and maintainability.