What is Scalar Type in GraphQL: Simple Explanation and Examples
scalar type represents a basic, indivisible data value like a number, string, or boolean. Scalars are the simplest data types used to define the shape of data in a GraphQL schema.How It Works
Think of scalar types in GraphQL as the basic building blocks of data, similar to how letters form words. They represent single, simple values that cannot be broken down further, such as a number or text. For example, a person's age might be a number, and their name might be text. These are scalar types.
When you create a GraphQL schema, you use scalar types to define the kind of data each field holds. This helps GraphQL understand what kind of data to expect and how to handle it. Scalars are like the smallest pieces of a puzzle that fit together to form the full picture of your data.
Example
This example shows a GraphQL schema defining scalar types for a user’s name, age, and active status.
type User { name: String age: Int isActive: Boolean } type Query { getUser: User }
When to Use
Use scalar types whenever you need to represent simple data values in your GraphQL API. They are perfect for fields like names, numbers, dates, or true/false flags. Scalars keep your schema clear and easy to understand.
For example, if you are building a user profile API, you would use scalar types for fields like username (String), age (Int), and isVerified (Boolean). Scalars are the foundation before you move on to more complex types like objects or lists.
Key Points
- Scalar types represent simple, indivisible data values.
- Common built-in scalars include
Int,Float,String,Boolean, andID. - Scalars define the basic data shape in a GraphQL schema.
- Use scalars for fields that hold single values like numbers or text.