0
0
GraphqlHow-ToBeginner · 3 min read

How to Define Type in GraphQL Schema: Syntax and Examples

In GraphQL, you define a type using the type keyword followed by the type name and a set of fields inside curly braces. Each field has a name and a type, such as String or Int, which tells GraphQL what kind of data to expect.
📐

Syntax

To define a type in GraphQL schema, use the type keyword, then the type name, and inside curly braces list the fields with their types. Each field must have a name and a type, and you can use ! to mark a field as required (non-nullable).

  • type: keyword to declare a new type
  • TypeName: the name of your type (usually capitalized)
  • fieldName: the name of a field inside the type
  • FieldType: the data type of the field (e.g., String, Int, Boolean)
  • !: means the field is required and cannot be null
graphql
type TypeName {
  fieldName: FieldType
  anotherField: AnotherType!
}
💻

Example

This example shows how to define a simple User type with fields for id, name, and age. The id and name fields are required, while age is optional.

graphql
type User {
  id: ID!
  name: String!
  age: Int
}
Output
Defines a User type with required id and name fields and an optional age field.
⚠️

Common Pitfalls

Common mistakes when defining types include forgetting to capitalize the type name, missing the colon between field name and type, and not marking required fields with !. Also, using lowercase for type names or field types will cause errors.

graphql
type user {
  id: ID!
  name: string
}

# Correct version:
type User {
  id: ID!
  name: String!
}
📊

Quick Reference

ElementDescriptionExample
typeKeyword to define a new typetype User { ... }
TypeNameName of the type, capitalizedUser, Post, Comment
fieldNameName of a field inside the typeid, name, age
FieldTypeData type of the fieldString, Int, Boolean, ID
!Marks a field as required (non-null)id: ID!

Key Takeaways

Use the 'type' keyword followed by a capitalized name to define a GraphQL type.
Each field inside a type must have a name and a type, separated by a colon.
Add '!' after a type to make a field required and non-nullable.
Common errors include lowercase type names and missing colons.
Use built-in scalar types like String, Int, Boolean, and ID for fields.