Types in Fern Definition
Types describe the data model of your API.
Built-in types
Custom types
Creating your own types is easy in Fern!
Objects
The most common custom types are objects.
In Fern, you use the "properties"
key to create an object:
These represent JSON objects:
You can also use extends to compose objects:
You can extend multiple objects:
Aliases
An Alias type is a renaming of an existing type. This is usually done for clarity.
Enums
An enum represents a string with a set of allowed values.
In Fern, you use the "enum"
key to create an enum:
Enum names are restricted to A-Z
, a-z
, 0-9
, and _
to ensure that generated code can compile across all of the languages that Fern can output. If you have an enum that doesn’t follow this convention, you can use the "name"
key to specify a custom name:
Discriminated Unions
Fern supports tagged unions (a.k.a. discriminated unions). Unions are useful for
polymorphism. This is similar to the oneOf
concept in OpenAPI.
In Fern, you use the "union"
key to create an union:
In JSON, unions have a discriminant property to differentiate between
different members of the union. By default, Fern uses "type"
as the
discriminant property:
You can customize the discriminant property using the “discriminant” key:
This corresponds to a JSON object like this:
Undiscriminated Unions
Undiscriminated unions are similar to discriminated unions, however you don’t need to define an explicit discriminant property.
Generics
Fern supports shallow generic objects, to minimize code duplication. You can define a generic for reuse like so:
Now, you can instantiate generic types as a type alias:
You can now freely use this type as if it were any other type! Note, generated code will not use generics. The above example will be generated in typescript as:
Documenting types
You can add documentation for types. These docs are passed into the compiler, and are incredibly useful in the generated outputs (e.g., docstrings in SDKs).
Validating types
You can add validation constraints to your types (both aliases and references) to ensure data integrity. Validation constracts are automatically enforced in generated SDKs.
String validation reference
String types support several validation constraints.
Minimum number of characters required
Maximum number of characters allowed
Regular expression pattern that the string must match
String format specification (e.g., “email”, “uri”, “date-time”)
Number validation reference
Number types (including integer
, long
, and double
) support several validation constraints.
Minimum value (inclusive by default)
Maximum value (inclusive by default)
When true, the minimum value is exclusive (value must be greater than min)
When true, the maximum value is exclusive (value must be less than max)
Value must be a multiple of this number