BudiBadu Logo
Samplebadu

GraphQL by Example: Scalar Types

June 2018 Specification

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:

  • Int represents signed 32-bit integers for whole numbers
  • Float represents signed double-precision floating-point values for decimals
  • String represents UTF-8 character sequences for text data
  • Boolean represents true or false values for logical conditions
  • ID represents 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

3
id: ID unique identifier scalar, serialized as string for caching and refetching.
6
username: String UTF-8 character sequence for text data.
9
age: Int signed 32-bit integer for whole numbers.
12
score: Float double-precision floating-point for decimal numbers.