![]() |
VOOZH | about |
The GraphQL type system defines the structure and capabilities of a GraphQL server by specifying data types and schema. It ensures valid queries and acts as a contract between the client and server.
GraphQL provides various types to define data structure, operations, and constraints within a schema.
These types are primitive data types. These data types tend to store only a single value. GraphQL offers various default scalar types:
Syntax:
scalar Int
scalar Float
scalar String
scalar Boolean
scalar IDExample: Define a Post type that includes a title and content, both of which are strings.
type Post {
id: ID!
title: String!
content: String!
createdAt: DateTime!
} Object type represents a structured group of related fields in a GraphQL schema.
Syntax:
type Person {
id: ID!
name: String!
age: Int!
address: Address!
}Example: To store the basic structure for storing employee information in a GraphQL schema.
To define an object type
type Employee {
emp_id:ID
firstname: String
age: Int
salary:Float
} To define a GraphQL schema
type Query
{
emp_details:[Employee]
} Query type defines the entry points for fetching data from the server.
Syntax:
type Query {
person(id: ID!): Person
allPersons: [Person!]!
}Example: Greet message from the server in a GraphQL query.
type Query {
greeting: String
}Mutation type defines the entry points for modifying data in the server.
Syntax:
type Mutation {
createPerson(name: String!, age: Int!): Person!
updatePerson(id: ID!, name: String, age: Int): Person
deletePerson(id: ID!): Boolean
}Example: To add a new employee to the system.
type Mutation {
addEmployee(firstName: String, lastName: String): Employee
} Enum type represents a fixed set of predefined values in the GraphQL type system.
Syntax:
type enum_name{
val_1
val_2
}Example:
type Days_of_Week{
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
} List type represents a collection of multiple values of the same type in GraphQL.
Syntax:
field:[data_type]
Example: Returns a list of strings, representing a to-do list.
type Query {
todo: [String]
} Non-nullable type ensures that a field must always return a value and cannot be null.
Syntax:
field:data_type!Example: Define the field for the employee where the employee if can't be NULL.
type Employee {
emp_id:ID!
firstName:String
lastName:String
}