Skip to content

✨ Allow all type values from json schema 2020-12 #13639

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

sammasak
Copy link

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
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? 😄

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.

2 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy