Can I specify an external data source as the acceptable values of an enum in an openapi schema object?

Viewed 103

I'm working on an openapi (3.0.2) specification for a spring client/server. I want to be able to specify that certain fields have a limited and finite set of values -- an enum. Trouble is, I want to reference an external data file of complex objects to serve as the limited and finite list. Like so:

The reference data:

“Countries”: [
    {
        “name”: “United States of America”,
        “code3”: “USA”,
        “code2”: “US”
    },
    {
        “name”: “Canada”,
        “code3”: “CAN”,
        “code2”: “CA”
    },
    {
        “name”: “Mexico”,
        “code3”: “MEX”,
        “code2”: “MX”
    }
]

and what I want to be able to do is require an input parameter that specifically references code2:

“get”: {
    “parameters”: [
        “countryCode2”: {
            “in”: “query”,
            “schema”: {
                “$ref”: “referencefile.json/#/Countries/code2”
            }
        }
    ]
}

I'm pretty sure this definition breaks, but I'm wondering if this is even possible without tearing my reference files apart.

1 Answers

The enum in schemas requires an inline list of values and does not support $ref or JSONPath queries.

"get": {
    "parameters": [
        {
            "in": "query",
            "name": "countryCode2",
            "schema": {
                "type": "string",
                "enum": ["US", "CA", "MX"]
            }
        }
    ]
}

What you could do is write a script that would generate OpenAPI-compatible schema definitions based on your reference data file, then you can reference those schemas in your API definition. For example:

code2.json:

{
  "type": "string",
  "enum": ["US", "CA", "MX"]
}

API definition:

"get": {
    "parameters": [
        {
            "in": "query",
            "name": "countryCode2",
            "schema": {
                "$ref": "path/to/code2.json"
            }
        }
    ]
}
Related