0
0
GraphQLquery~5 mins

Why schema defines the API contract in GraphQL

Choose your learning style9 modes available
Introduction

A schema in GraphQL clearly shows what data can be asked for and what will be given back. It acts like a promise between the server and the user.

When you want to make sure everyone knows exactly what data they can get from your API.
When you want to avoid confusion about what information is available or required.
When you want to help developers build apps that work smoothly with your data.
When you want to catch mistakes early by checking if queries match the schema.
When you want to keep your API organized and easy to understand.
Syntax
GraphQL
type TypeName {
  fieldName: FieldType
  anotherField: AnotherType
}

schema {
  query: QueryType
  mutation: MutationType
}
The schema defines types and their fields, showing what data can be requested.
It acts as a contract, so clients know what queries and mutations are allowed.
Examples
This schema says you can ask for a list of books, each with a title and author.
GraphQL
type Book {
  title: String
  author: String
}

type Query {
  books: [Book]
}
This schema defines a user with required id and name, and optional email. You can query a user by id.
GraphQL
type User {
  id: ID!
  name: String!
  email: String
}

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

This simple schema defines a query called 'greeting' that returns a string.

GraphQL
type Query {
  greeting: String
}

schema {
  query: Query
}
OutputSuccess
Important Notes

The schema helps tools and developers understand what data is available.

Changing the schema means changing the contract, so be careful to keep it consistent.

Summary

The schema is like a menu showing what data you can order from the API.

It makes sure everyone agrees on what data is possible and how to ask for it.

This agreement helps avoid errors and makes building apps easier.