0
0
GraphQLquery~5 mins

Schema definition in GraphQL

Choose your learning style9 modes available
Introduction

A schema defines the shape and rules of your data in GraphQL. It tells what data you can ask for and how it is connected.

When you want to describe what data your GraphQL API can provide.
When you need to set rules for what types of data clients can request.
When you want to organize your data into types and fields clearly.
When you want to ensure clients only ask for valid data.
When you want to connect different pieces of data in a structured way.
Syntax
GraphQL
type TypeName {
  fieldName: FieldType
  anotherField: AnotherType
}

schema {
  query: QueryType
  mutation: MutationType
}

type defines a new object type with fields.

The schema block sets the entry points for queries and mutations.

Examples
This defines a Book type with three fields: title, author, and pages.
GraphQL
type Book {
  title: String
  author: String
  pages: Int
}
This defines the Query type with two fields: one to get all books and one to get a book by its ID.
GraphQL
type Query {
  books: [Book]
  book(id: ID!): Book
}
This sets the Query type as the entry point for queries.
GraphQL
schema {
  query: Query
}
Sample Program

This schema defines a User type with id, name, and email fields. It also defines a Query type to get all users or a single user by ID. The schema entry point is set to Query.

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

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

schema {
  query: Query
}
OutputSuccess
Important Notes

Use ! after a type to mark it as required (non-nullable).

Square brackets [] indicate a list of items.

Schema must have at least a query type defined.

Summary

A schema defines the data types and queries your GraphQL API supports.

Use type to create object types with fields.

The schema block sets the main entry points like query and mutation.