Defining Fields of Type SET Within OpenAPI/Swagger

Nick Poulos
2 min readFeb 19, 2020

--

During a recent API design session, I came across a data type that should have taken three seconds to define, but ended up causing a little head scratching. And that task is — defining a SET data type within your Open API spec.

Seems easy enough right? And it is of course…but after several unhelpful Google queries later I still couldn’t quite get it right.

Now, I do realize I could have just made a new type or object specifically for this little data set.

/path/to/my/api:
get:
summary: My Custom API
description: |
Gets a List of FooBar IDs
produces:
- application/json
tags:
- FooBar
responses:
"200":
description: successful operation
schema:
$ref: "#/definitions/MyCustomType"

...

MyCustomType:
type: object
properties:
myCustomObject
type: ??? # list of string?

But that seemed like total overkill for what I needed, very verbose, and the data within would not quite live up to the name ‘object’. There just had to be a better way, right?? :).

For those who need a refresher, a `SET` is a kind of obscure little field type, found in MySQL, that is essentially an array of ENUM values. Say we have a SET field called “social_type”, with possible values of facebook twitter, instagram. That means “social_type” could a single value, like just facebook or twitter, just like your typical ENUM. However it could also be set to facebook, twitter or twitter, instagram or even all 3, facebook, twitter, instagram. So a SET holds one or more possible ENUM values, or an ARRAY of enums. And that is exactly how we should define it in our spec.

share_type:
type: array
enum:
- facebook
- pinterest
- tumblr
- twitter
- linkedin
uniqueItems: true
items: {}

I should point out the necessary uniqueItems flag that was set to TRUE here, as a SET cannot have a repeated value.

Super easy. Hopefully it saved somebody a few min Googling, thanks for reading.

--

--

Nick Poulos
Nick Poulos

Responses (1)