Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@sammasak
Copy link
Contributor

Allow Union Types in OpenAPI Schemas

This PR addresses an issue with how union types for the "type" field are validated in FastAPI's OpenAPI generation. Currently, only a string is allowed for the type definition even though the JSON Schema specification (Section 6.1.1) permits the value to be either a string or an array of unique string values. This discrepancy can lead to confusion or incorrect schema validation when using union types.

Example here that throws pydantic validation error:

# example.py 
# uv run --no-project example.py
# /// script
# requires-python = ">=3.12"
# dependencies = [
#     "fastapi",
#     "pydantic",
# ]
# ///


from fastapi.openapi.models import OpenAPI
from pydantic import ValidationError

openapi_dict = {
    "openapi": "3.1.0",
    "info": {"title": "Type Examples with Union Types", "version": "1.0.0"},
    "components": {
        "schemas": {
            "UnionStringOrNumber": {
                "type": ["string", "number"],
                "description": "An instance is valid if it is either a string or a number.",
                "example": "example as string",
            },
        }
    },
}


def test_openapi_type() -> None:
    try:
        _ = OpenAPI(**openapi_dict)
    except ValidationError as e:
        # Expecting this to raise a ValidationError
        print(f"Validation error: {e}")
        return

    raise NotImplementedError("This should not be reached.")


if __name__ == "__main__":
    test_openapi_type()
    print("Test passed!")

Addressed by introducingTypeValue, defined as an annotated literal that encompasses the valid JSON Schema types.

And updating the Schema model to use the literal values.

After these changes the validation error is removed.

@sammasak sammasak marked this pull request as draft April 23, 2025 12:35
@sammasak sammasak marked this pull request as ready for review April 23, 2025 13:22
@svlandeg svlandeg added the feature New feature or request label Apr 28, 2025
@svlandeg svlandeg changed the title Adding type values following the allowed values from json schema 2020-12 ✨ Allow all type values from json schema 2020-12 Apr 28, 2025
@sammasak
Copy link
Contributor Author

sammasak commented May 5, 2025

Hey @svlandeg thanks for adding the label, what does the review process look like and can I help out in anyway? 😄

@YuriiMotov
Copy link
Member

YuriiMotov commented Jul 16, 2025

Similar, but set[str] is used: #12528

I personally like the approach with list more.

@sammasak, could you please add tests?

@sammasak sammasak force-pushed the adding-type-values-following-json-schema branch from 3ae5fab to 3cd4f27 Compare July 24, 2025 13:57
@sammasak
Copy link
Contributor Author

sammasak commented Jul 24, 2025

@YuriiMotov Added some tests, but the change in this PR is quite small and is only made to allow for type to be a str and list. But since there is no field validator for type its still possible to break the json schema. (by setting type to a empty list or by adding duplicates. https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1 )

But I think this is a good start and more validation can be added later. wdyt?

@github-actions github-actions bot removed the waiting label Jul 24, 2025
Copy link
Member

@YuriiMotov YuriiMotov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's reduce the number of test a bit :)
Just test that all valid types are accepted and maybe add one test for validation error on passing incorrect type

Added some tests, but the change in this PR is quite small and is only made to allow for type to be a str and list. But since there is no field validator for type its still possible to break the json schema. (by setting type to a empty list or by adding duplicates
But I think this is a good start and more validation can be added later. wdyt?

I agree, no need to add this validation now.

@sammasak sammasak force-pushed the adding-type-values-following-json-schema branch from 86795bb to 13f918c Compare July 24, 2025 15:14
@sammasak sammasak force-pushed the adding-type-values-following-json-schema branch from 13f918c to 9379506 Compare July 24, 2025 15:16
@YuriiMotov YuriiMotov changed the title ✨ Allow all type values from json schema 2020-12 ✨ Allow array values for OpenAPI schema type field Jul 24, 2025
Copy link
Member

@YuriiMotov YuriiMotov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@sammasak, thanks!

Copy link
Member

@tiangolo tiangolo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, thanks! 🚀

I tweaked it a bit to put the OpenAPI types and related on the same file, it should be ready now. 🍰

@tiangolo tiangolo enabled auto-merge (squash) September 20, 2025 17:46
@tiangolo tiangolo merged commit 8ede272 into fastapi:master Sep 20, 2025
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants