0
0
GraphqlHow-ToBeginner · 4 min read

How to Define Schema in GraphQL: Syntax and Examples

In GraphQL, you define a schema using the type keyword to declare object types and their fields, specifying the data structure clients can query. The schema includes Query and optionally Mutation types to define read and write operations respectively.
📐

Syntax

A GraphQL schema is defined using type declarations. Each type has fields with names and data types. The Query type defines read operations, and Mutation defines write operations. Scalars like String, Int, and Boolean represent basic data types.

graphql
type Query {
  fieldName: FieldType
}

type Mutation {
  updateField(input: InputType): ReturnType
}

type ObjectType {
  id: ID!
  name: String
  age: Int
}
💻

Example

This example shows a simple schema with a User type, a Query to get users, and a Mutation to add a user.

graphql
type User {
  id: ID!
  name: String!
  age: Int
}

type Query {
  users: [User!]!
}

type Mutation {
  addUser(name: String!, age: Int): User
}
Output
Query users returns a list of User objects with id, name, and age fields. Mutation addUser creates a new User with name and optional age.
⚠️

Common Pitfalls

  • Forgetting to mark required fields with ! can cause unexpected null values.
  • Not defining a Query type will make the schema unusable for fetching data.
  • Using incorrect scalar types or misspelling type names leads to schema errors.
  • Confusing type with input types for mutations can cause validation issues.
graphql
Wrong:

type Mutation {
  addUser(user: User): User
}

Right:

input UserInput {
  name: String!
  age: Int
}

type Mutation {
  addUser(user: UserInput!): User
}
📊

Quick Reference

ConceptDescriptionExample
typeDefines an object with fieldstype User { id: ID! name: String! }
QueryRoot type for read operationstype Query { users: [User!]! }
MutationRoot type for write operationstype Mutation { addUser(name: String!): User }
ScalarBasic data typesString, Int, Boolean, ID
InputDefines input object for mutationsinput UserInput { name: String! age: Int }

Key Takeaways

Define your schema using type for objects and Query for read operations.
Use Mutation type to define write operations with input types.
Mark required fields with ! to avoid null values.
Always include a Query type to enable data fetching.
Use input types for mutation arguments instead of object types.