0
0
GraphQLquery~5 mins

Type definitions in GraphQL

Choose your learning style9 modes available
Introduction

Type definitions tell GraphQL what kinds of data you can ask for and what shape it has. They help make sure your queries get the right data.

When you want to describe the shape of data your API can send or receive.
When you need to define what fields an object has and their types.
When you want to create custom data types for your API.
When you want to specify what queries or mutations your API supports.
When you want to ensure clients and servers agree on data structure.
Syntax
GraphQL
type TypeName {
  fieldName: FieldType
  anotherField: AnotherType
}

# Example:
type Book {
  title: String
  pages: Int
}

Type names start with a capital letter.

Fields inside types have a name and a type, separated by a colon.

Examples
This defines a User type with an ID, name, and age.
GraphQL
type User {
  id: ID
  name: String
  age: Int
}
This defines a Query type with a getUser field that takes a non-null ID and returns a User.
GraphQL
type Query {
  getUser(id: ID!): User
}
This defines a Book type where author is another type User.
GraphQL
type Book {
  title: String
  author: User
  pages: Int
}
Sample Program

This example defines a Person type and a Query type to get a person by their ID.

GraphQL
type Person {
  id: ID
  name: String
  email: String
}

type Query {
  personById(id: ID!): Person
}
OutputSuccess
Important Notes

Type definitions do not return data themselves; they define the shape of data.

Use built-in scalar types like String, Int, ID, Boolean, and Float for simple fields.

You can create custom types by combining fields of different types.

Summary

Type definitions describe the shape and types of data in GraphQL.

They help clients know what data they can ask for and how it looks.

Types include objects, queries, mutations, and scalars.