Only one with OneOf

In the example snippets below, path parameter “id” can be either an ID or username.
The developer uses the oneOf keyword to define the parameter.
But there’s a bug.
Can you spot it?

"parameters": [
    {
        "name": "id",
        "in": "path",
        "description": "The ID or username of the member",
        "required": true,
        "schema": {
            "oneOf": [
                {
                    "$ref": "#/components/schemas/ID"
                },
                {
                    "type": "string"
                }
             ]
         }
     }
]
...
"components": {
    "schemas": {
        "ID": {
            "type": "string",
            "pattern": "^[0-9a-fA-F]{24}$"
        }
    }
}

The problem here is that a valid ID value will always fail schema validation.

The ‘oneOf’ key represents an exclusive OR condition, which means the data must match exactly one of the subschemas.

In this case, since the second subschema is loosely defined as “string” therefore a valid ID (which must also be a string) will always match both subschema’s (not exactly one), and so will always fail.

The solution would be to add more precise constraints to the second subschema.

:wink:

1 Like