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
| Element | Description | Example |
|---|---|---|
| type | Keyword to define a new type | type User { ... } |
| TypeName | Name of the type, capitalized | User, Post, Comment |
| fieldName | Name of a field inside the type | id, name, age |
| FieldType | Data type of the field | String, 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.