What is a GraphQL Schema?

A GraphQL schema is a crucial component of a GraphQL API. It defines the structure of the API, specifying the types of data that can be queried or mutated, as well as the relationships between those types. The schema serves as a contract between the client and the server, ensuring that both parties understand the data that can be requested and the operations that can be performed.

Key Features of a GraphQL Schema

  • Strongly Typed: GraphQL schemas are strongly typed, meaning that each field in the schema has a specific type. This helps in validating queries and ensuring that clients receive the expected data.
  • Declarative: The schema explicitly defines what data is available and how it can be accessed, making it easier for developers to understand the API.
  • Self-Documenting: The schema can be introspected, allowing clients to query the schema itself to discover available types, fields, and operations.

Components of a GraphQL Schema

A GraphQL schema consists of several components, including object types, queries, mutations, and subscriptions. Below are explanations of each component:

1. Object Types

Object types represent the data structures in your API. Each object type has fields that define the properties of that type.


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

2. Queries

Queries define the read operations that clients can perform. Each query specifies the data that can be fetched.


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

3. Mutations

Mutations define the write operations that clients can perform, such as creating, updating, or deleting data.


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

4. Subscriptions

Subscriptions allow clients to receive real-time updates when data changes. This is useful for applications that require live data.


type Subscription {
userCreated: User
}

Sample Complete Schema

Here’s an example of a complete GraphQL schema that includes object types, queries, mutations, and subscriptions:


schema {
query: Query
mutation: Mutation
subscription: Subscription
}

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

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

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

type Subscription {
userCreated: User
}

Conclusion

A GraphQL schema is a foundational element of a GraphQL API, providing a clear and structured way to define the data and operations available to clients. By understanding how to create and use schemas, developers can build robust and flexible APIs that meet the needs of their applications.