GraphQL by Example: Scalar Types
Defining primitive data types with this code example showing built-in scalar types including ID, String, Int, Float, and Boolean, scalar type characteristics as leaf values, custom scalar capabilities, and serialization behavior.
Code
type User {
# ID: A unique identifier (serialized as string)
id: ID
# String: UTF-8 character sequence
username: String
# Int: Signed 32-bit integer
age: Int
# Float: Signed double-precision floating-point value
score: Float
# Boolean: true or false
isActive: Boolean
}Explanation
Scalar types represent leaf values in GraphQL queries, meaning they cannot have sub-fields and resolve to concrete data values rather than objects. GraphQL includes five built-in scalar types: Int for signed 32-bit integers, Float for signed double-precision floating-point values, String for UTF-8 character sequences, Boolean for true or false values, and ID for unique identifiers.
Built-in GraphQL scalar types include:
Intrepresents signed 32-bit integers for whole numbersFloatrepresents signed double-precision floating-point values for decimalsStringrepresents UTF-8 character sequences for text dataBooleanrepresents true or false values for logical conditionsIDrepresents unique identifiers, serialized as strings but semantically distinct
The ID scalar is special, representing unique identifiers often used to refetch objects or as cache keys. While serialized as strings in JSON, declaring a field as ID in the schema communicates it's a machine-readable key rather than human-readable text. GraphQL implementations allow defining custom scalars like Date, UUID, or Email using the scalar keyword, enabling custom validation and formatting logic at the schema level.
Code Breakdown
id: ID unique identifier scalar, serialized as string for caching and refetching.username: String UTF-8 character sequence for text data.age: Int signed 32-bit integer for whole numbers.score: Float double-precision floating-point for decimal numbers.
