Getting Started With OpenAPI - Data Types

Getting Started With OpenAPI - Data Types

In this tutorial you are going to learn the data types that are available when using OpenAPI to define your API specification. In one of my posts, I described how you could integrate OpenAPI into a Node Express Application , now let's learn how we can actually use it after integrating it into our app.

What is OpenAPI Specification?

The OpenAPI Specification, previously known as the Swagger Specification, is a specification for machine-readable interface files for describing, producing, consuming, and visualizing RESTful web services - Wikipedia

What Is A Data Type?

In computer science and computer programming, a data type or simply type is an attribute of data which tells the compiler or interpreter how the programmer intends to use the data - Wikipedia

Just like in many typed languages OpenAPI has a type system that covers the most common data types you will find in most programming languages. These types include

  • string
  • number
  • integer
  • boolean
  • array
  • object

OpenAPI also provides certain modifiers to allow for describing certain data types more accurately. For instance, with the format modifier you can specify whether a given string is a

  • date
  • date-time
  • password
  • byte
  • binary

It even goes ahead to state that the format modifier is an open value, so you can use any formats, even those not defined by the OpenAPI Specification, such as

  • email
  • uuid
  • uri
  • hostname
  • ipv4
  • ipv6
  • and others

There is also the pattern modifier which allows you to specify a given pattern or regular expression for a data type. Putting everything we discussed up to this point an example will look like this

ssn:
  type: string
  pattern: '^\d{3}-\d{2}-\d{4}$'

Gotchas

OpenAPI 3.0 does not have an explicit null type as in JSON Schema, but you can use nullable: true to specify that the value may be null. Note that null is different from an empty string "".

Final Note

There are several other things you can do, mix, and match these data types to achieve your desired results. The official docs does a good job of explaining these other uses with examples. Let's connect on Twitter and LinkedIn