GraphQL vs RESTπ± Beginner
The absolute foundation of any GraphQL API is the Schema. It acts as an iron-clad contract between the frontend client and the backend server, defining exactly what data can be requested.
What is a Schema?
A Schema is a collection of custom Types (representing your database tables or objects) written in a syntax called Schema Definition Language (SDL). It explicitly defines the fields an object has, and whether those fields are strings, integers, or relationships to other objects.
Why is the Schema Mandatory?
When a frontend client sends a query to the server, the GraphQL engine immediately checks the query against the Schema. If the frontend asks for a field that doesn't exist, the engine rejects the request instantly before it ever hits your database logic, ensuring massive security and stability.
How to Write a Schema
You define standard Object types, and then use the mandatory Query type to define how clients can actually fetch them.
# 1. Define your custom Object Type
type User {
id: ID! # The exclamation mark (!) means this field is mandatory/non-null
name: String!
email: String
age: Int
}
# 2. Define the Entry Points (How clients fetch the data)
type Query {
getUser(id: ID!): User # Returns a single user
getAllUsers: [User!]! # Returns a mandatory array of Users
}