strings
The string type is one of the most used and most flexible primitive types in OpenAPI. It supports a number of formats, patterns and other validations that overlay constraints to the type of data represented. This is not just helpful for documentation and validation, but it can help with mapping to types in various languages when using OpenAPI for code generation.
Formats
The string type can contain anything, from passwords, IP addresses, email addresses, long form text, binary data, pretty much anything. To help describe the data in the string more specifically, OpenAPI supports a format
keyword:
Here are a few common formats that are likely to pop up.
Common String Formats
The format property has grown substantially over time, and a new Format Registry
- base64url
- binary
- byte
- char
- commonmark
- date-time
- date
- decimal
- decimal128
- double
- duration
- float
- hostname
- html
- http-date
- idn-email
- idn-hostname
- int16
- int32
- int64
- int8
- ipv4
- ipv6
- iri-reference
- iri
- json-pointer
- media-range
- password
- regex
- relative-json-pointer
- sf-binary
- sf-boolean
- sf-decimal
- sf-integer
- sf-string
- sf-token
- time
- uint8
- uri-reference
- uri-template
- uri
- uuid
This list is huge already and likely to grow over time. Not all tooling will understand every single one, but that’s ok because format is an extensible property in OpenAPI: anyone could put any value in there, and if a tool knows what it means, it can do something with it.
Examples
Patterns
The string type also has an associated pattern
keyword which accepts a regular expression, which can help further define a string when no particular format is exactly appropriate.
The regular expression syntax is the one defined in JavaScript (ECMA 262 pattern
keyword is part of the JSON Schema schema
keyword, so you can read more about Regular Expressions
Examples
Example of a string defined with a regex pattern:
When to use pattern or format
Pattern is used primarily for validation, but format is sometimes only treated as an informative annotation.
In some cases it might be a good idea to provide a pattern as well as a format, just to make sure validation is run as expected.
Last updated on