fastapi/openapi/models.py PYTHON 436 lines View on github.com → Search inside
1from collections.abc import Callable, Iterable, Mapping2from enum import Enum3from typing import Annotated, Any, Literal, Optional, Union45from fastapi._compat import with_info_plain_validator_function6from fastapi.logger import logger7from pydantic import (8    AnyUrl,9    BaseModel,10    Field,11    GetJsonSchemaHandler,12)13from typing_extensions import TypedDict14from typing_extensions import deprecated as typing_deprecated1516try:17    import email_validator1819    assert email_validator  # make autoflake ignore the unused import20    from pydantic import EmailStr21except ImportError:  # pragma: no cover2223    class EmailStr(str):  # type: ignore[no-redef]24        @classmethod25        def __get_validators__(cls) -> Iterable[Callable[..., Any]]:26            yield cls.validate2728        @classmethod29        def validate(cls, v: Any) -> str:30            logger.warning(31                "email-validator not installed, email fields will be treated as str.\n"32                "To install, run: pip install email-validator"33            )34            return str(v)3536        @classmethod37        def _validate(cls, __input_value: Any, _: Any) -> str:38            logger.warning(39                "email-validator not installed, email fields will be treated as str.\n"40                "To install, run: pip install email-validator"41            )42            return str(__input_value)4344        @classmethod45        def __get_pydantic_json_schema__(46            cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler47        ) -> dict[str, Any]:48            return {"type": "string", "format": "email"}4950        @classmethod51        def __get_pydantic_core_schema__(52            cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]53        ) -> Mapping[str, Any]:54            return with_info_plain_validator_function(cls._validate)555657class BaseModelWithConfig(BaseModel):58    model_config = {"extra": "allow"}596061class Contact(BaseModelWithConfig):62    name: str | None = None63    url: AnyUrl | None = None64    email: EmailStr | None = None656667class License(BaseModelWithConfig):68    name: str69    identifier: str | None = None70    url: AnyUrl | None = None717273class Info(BaseModelWithConfig):74    title: str75    summary: str | None = None76    description: str | None = None77    termsOfService: str | None = None78    contact: Contact | None = None79    license: License | None = None80    version: str818283class ServerVariable(BaseModelWithConfig):84    enum: Annotated[list[str] | None, Field(min_length=1)] = None85    default: str86    description: str | None = None878889class Server(BaseModelWithConfig):90    url: AnyUrl | str91    description: str | None = None92    variables: dict[str, ServerVariable] | None = None939495class Reference(BaseModel):96    ref: str = Field(alias="$ref")979899class Discriminator(BaseModel):100    propertyName: str101    mapping: dict[str, str] | None = None102103104class XML(BaseModelWithConfig):105    name: str | None = None106    namespace: str | None = None107    prefix: str | None = None108    attribute: bool | None = None109    wrapped: bool | None = None110111112class ExternalDocumentation(BaseModelWithConfig):113    description: str | None = None114    url: AnyUrl115116117# Ref JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation#name-type118SchemaType = Literal[119    "array", "boolean", "integer", "null", "number", "object", "string"120]121122123class Schema(BaseModelWithConfig):124    # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu125    # Core Vocabulary126    schema_: str | None = Field(default=None, alias="$schema")127    vocabulary: str | None = Field(default=None, alias="$vocabulary")128    id: str | None = Field(default=None, alias="$id")129    anchor: str | None = Field(default=None, alias="$anchor")130    dynamicAnchor: str | None = Field(default=None, alias="$dynamicAnchor")131    ref: str | None = Field(default=None, alias="$ref")132    dynamicRef: str | None = Field(default=None, alias="$dynamicRef")133    defs: dict[str, "SchemaOrBool"] | None = Field(default=None, alias="$defs")134    comment: str | None = Field(default=None, alias="$comment")135    # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s136    # A Vocabulary for Applying Subschemas137    allOf: list["SchemaOrBool"] | None = None138    anyOf: list["SchemaOrBool"] | None = None139    oneOf: list["SchemaOrBool"] | None = None140    not_: Optional["SchemaOrBool"] = Field(default=None, alias="not")141    if_: Optional["SchemaOrBool"] = Field(default=None, alias="if")142    then: Optional["SchemaOrBool"] = None143    else_: Optional["SchemaOrBool"] = Field(default=None, alias="else")144    dependentSchemas: dict[str, "SchemaOrBool"] | None = None145    prefixItems: list["SchemaOrBool"] | None = None146    items: Optional["SchemaOrBool"] = None147    contains: Optional["SchemaOrBool"] = None148    properties: dict[str, "SchemaOrBool"] | None = None149    patternProperties: dict[str, "SchemaOrBool"] | None = None150    additionalProperties: Optional["SchemaOrBool"] = None151    propertyNames: Optional["SchemaOrBool"] = None152    unevaluatedItems: Optional["SchemaOrBool"] = None153    unevaluatedProperties: Optional["SchemaOrBool"] = None154    # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural155    # A Vocabulary for Structural Validation156    type: SchemaType | list[SchemaType] | None = None157    enum: list[Any] | None = None158    const: Any | None = None159    multipleOf: float | None = Field(default=None, gt=0)160    maximum: float | None = None161    exclusiveMaximum: float | None = None162    minimum: float | None = None163    exclusiveMinimum: float | None = None164    maxLength: int | None = Field(default=None, ge=0)165    minLength: int | None = Field(default=None, ge=0)166    pattern: str | None = None167    maxItems: int | None = Field(default=None, ge=0)168    minItems: int | None = Field(default=None, ge=0)169    uniqueItems: bool | None = None170    maxContains: int | None = Field(default=None, ge=0)171    minContains: int | None = Field(default=None, ge=0)172    maxProperties: int | None = Field(default=None, ge=0)173    minProperties: int | None = Field(default=None, ge=0)174    required: list[str] | None = None175    dependentRequired: dict[str, set[str]] | None = None176    # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c177    # Vocabularies for Semantic Content With "format"178    format: str | None = None179    # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten180    # A Vocabulary for the Contents of String-Encoded Data181    contentEncoding: str | None = None182    contentMediaType: str | None = None183    contentSchema: Optional["SchemaOrBool"] = None184    # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta185    # A Vocabulary for Basic Meta-Data Annotations186    title: str | None = None187    description: str | None = None188    default: Any | None = None189    deprecated: bool | None = None190    readOnly: bool | None = None191    writeOnly: bool | None = None192    examples: list[Any] | None = None193    # Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object194    # Schema Object195    discriminator: Discriminator | None = None196    xml: XML | None = None197    externalDocs: ExternalDocumentation | None = None198    example: Annotated[199        Any | None,200        typing_deprecated(201            "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "202            "although still supported. Use examples instead."203        ),204    ] = None205206207# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents208# A JSON Schema MUST be an object or a boolean.209SchemaOrBool = Schema | bool210211212class Example(TypedDict, total=False):213    summary: str | None214    description: str | None215    value: Any | None216    externalValue: AnyUrl | None217218    __pydantic_config__ = {"extra": "allow"}  # type: ignore[misc]  # ty: ignore[invalid-typed-dict-statement]219220221class ParameterInType(Enum):222    query = "query"223    header = "header"224    path = "path"225    cookie = "cookie"226227228class Encoding(BaseModelWithConfig):229    contentType: str | None = None230    headers: dict[str, Union["Header", Reference]] | None = None231    style: str | None = None232    explode: bool | None = None233    allowReserved: bool | None = None234235236class MediaType(BaseModelWithConfig):237    schema_: Schema | Reference | None = Field(default=None, alias="schema")238    example: Any | None = None239    examples: dict[str, Example | Reference] | None = None240    encoding: dict[str, Encoding] | None = None241242243class ParameterBase(BaseModelWithConfig):244    description: str | None = None245    required: bool | None = None246    deprecated: bool | None = None247    # Serialization rules for simple scenarios248    style: str | None = None249    explode: bool | None = None250    allowReserved: bool | None = None251    schema_: Schema | Reference | None = Field(default=None, alias="schema")252    example: Any | None = None253    examples: dict[str, Example | Reference] | None = None254    # Serialization rules for more complex scenarios255    content: dict[str, MediaType] | None = None256257258class Parameter(ParameterBase):259    name: str260    in_: ParameterInType = Field(alias="in")261262263class Header(ParameterBase):264    pass265266267class RequestBody(BaseModelWithConfig):268    description: str | None = None269    content: dict[str, MediaType]270    required: bool | None = None271272273class Link(BaseModelWithConfig):274    operationRef: str | None = None275    operationId: str | None = None276    parameters: dict[str, Any | str] | None = None277    requestBody: Any | str | None = None278    description: str | None = None279    server: Server | None = None280281282class Response(BaseModelWithConfig):283    description: str284    headers: dict[str, Header | Reference] | None = None285    content: dict[str, MediaType] | None = None286    links: dict[str, Link | Reference] | None = None287288289class Operation(BaseModelWithConfig):290    tags: list[str] | None = None291    summary: str | None = None292    description: str | None = None293    externalDocs: ExternalDocumentation | None = None294    operationId: str | None = None295    parameters: list[Parameter | Reference] | None = None296    requestBody: RequestBody | Reference | None = None297    # Using Any for Specification Extensions298    responses: dict[str, Response | Any] | None = None299    callbacks: dict[str, dict[str, "PathItem"] | Reference] | None = None300    deprecated: bool | None = None301    security: list[dict[str, list[str]]] | None = None302    servers: list[Server] | None = None303304305class PathItem(BaseModelWithConfig):306    ref: str | None = Field(default=None, alias="$ref")307    summary: str | None = None308    description: str | None = None309    get: Operation | None = None310    put: Operation | None = None311    post: Operation | None = None312    delete: Operation | None = None313    options: Operation | None = None314    head: Operation | None = None315    patch: Operation | None = None316    trace: Operation | None = None317    servers: list[Server] | None = None318    parameters: list[Parameter | Reference] | None = None319320321class SecuritySchemeType(Enum):322    apiKey = "apiKey"323    http = "http"324    oauth2 = "oauth2"325    openIdConnect = "openIdConnect"326327328class SecurityBase(BaseModelWithConfig):329    type_: SecuritySchemeType = Field(alias="type")330    description: str | None = None331332333class APIKeyIn(Enum):334    query = "query"335    header = "header"336    cookie = "cookie"337338339class APIKey(SecurityBase):340    type_: SecuritySchemeType = Field(default=SecuritySchemeType.apiKey, alias="type")341    in_: APIKeyIn = Field(alias="in")342    name: str343344345class HTTPBase(SecurityBase):346    type_: SecuritySchemeType = Field(default=SecuritySchemeType.http, alias="type")347    scheme: str348349350class HTTPBearer(HTTPBase):351    scheme: Literal["bearer"] = "bearer"352    bearerFormat: str | None = None353354355class OAuthFlow(BaseModelWithConfig):356    refreshUrl: str | None = None357    scopes: dict[str, str] = {}358359360class OAuthFlowImplicit(OAuthFlow):361    authorizationUrl: str362363364class OAuthFlowPassword(OAuthFlow):365    tokenUrl: str366367368class OAuthFlowClientCredentials(OAuthFlow):369    tokenUrl: str370371372class OAuthFlowAuthorizationCode(OAuthFlow):373    authorizationUrl: str374    tokenUrl: str375376377class OAuthFlows(BaseModelWithConfig):378    implicit: OAuthFlowImplicit | None = None379    password: OAuthFlowPassword | None = None380    clientCredentials: OAuthFlowClientCredentials | None = None381    authorizationCode: OAuthFlowAuthorizationCode | None = None382383384class OAuth2(SecurityBase):385    type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type")386    flows: OAuthFlows387388389class OpenIdConnect(SecurityBase):390    type_: SecuritySchemeType = Field(391        default=SecuritySchemeType.openIdConnect, alias="type"392    )393    openIdConnectUrl: str394395396SecurityScheme = APIKey | HTTPBase | OAuth2 | OpenIdConnect | HTTPBearer397398399class Components(BaseModelWithConfig):400    schemas: dict[str, Schema | Reference] | None = None401    responses: dict[str, Response | Reference] | None = None402    parameters: dict[str, Parameter | Reference] | None = None403    examples: dict[str, Example | Reference] | None = None404    requestBodies: dict[str, RequestBody | Reference] | None = None405    headers: dict[str, Header | Reference] | None = None406    securitySchemes: dict[str, SecurityScheme | Reference] | None = None407    links: dict[str, Link | Reference] | None = None408    # Using Any for Specification Extensions409    callbacks: dict[str, dict[str, PathItem] | Reference | Any] | None = None410    pathItems: dict[str, PathItem | Reference] | None = None411412413class Tag(BaseModelWithConfig):414    name: str415    description: str | None = None416    externalDocs: ExternalDocumentation | None = None417418419class OpenAPI(BaseModelWithConfig):420    openapi: str421    info: Info422    jsonSchemaDialect: str | None = None423    servers: list[Server] | None = None424    # Using Any for Specification Extensions425    paths: dict[str, PathItem | Any] | None = None426    webhooks: dict[str, PathItem | Reference] | None = None427    components: Components | None = None428    security: list[dict[str, list[str]]] | None = None429    tags: list[Tag] | None = None430    externalDocs: ExternalDocumentation | None = None431432433Schema.model_rebuild()434Operation.model_rebuild()435Encoding.model_rebuild()

Code quality findings 1

Ensure functions have docstrings for documentation
info maintainability missing-docstring
def validate(cls, v: Any) -> str:

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings