Scalars and Enums
A review's rating should be a whole number, a book's genre should be one of four known shelves, and its publication date should be a date. If the schema just said "string" for all three, every client would have to guess the format and every server would have to re-check it. Scalars and enums make those rules part of the contract.
The rule
Scalars are single values; enums are single values from a fixed list.
GraphQL has five built-in scalars:
| Scalar | Holds | Bookshop example |
|---|---|---|
Int |
A signed 32-bit whole number | rating: Int! |
Float |
A double-precision decimal | price: Float! |
String |
UTF-8 text | title: String! |
Boolean |
true or false |
inStock: Boolean! |
ID |
A unique identifier | id: ID! |
ID is always sent as a string in responses, even if the database uses numbers. As an input it accepts a string or an integer, so book(id: 42) works and the resolver receives "42". Treat IDs as opaque labels, never as numbers to do maths with.
Scalars are checked on the way in. Passing 3.5 to an Int argument, or "five" to a Float, is an error before any resolver runs.
You can add custom scalars for values with a known format:
scalar Date @specifiedBy(url: "https://tools.ietf.org/html/rfc3339")
type Book {
published: Date
}The schema only declares the name; the server code decides how a Date is turned into JSON and how incoming values are checked. @specifiedBy points readers to the format's definition.
An enum is a scalar-like type whose value must be one of a listed set:
enum Genre {
FANTASY
MYSTERY
SCIENCE
HISTORY
}Enum values are written as bare words in queries (books(genre: MYSTERY)) and appear as strings in JSON, in both responses and variables ("genre": "MYSTERY"). By convention they are UPPER_CASE. Anything outside the list, such as ROMANCE, is rejected, and tools can autocomplete the valid values.