mirror of
https://github.com/fastapi/fastapi.git
synced 2026-09-14 13:36:21 +08:00
Additional Responses implementation
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
import logging
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
from typing import Any, Dict, List, Optional, Union, Type, ClassVar, Callable
|
||||
|
||||
from pydantic import BaseModel, Schema as PSchema
|
||||
from pydantic.types import UrlStr
|
||||
from pydantic.fields import Field
|
||||
|
||||
try:
|
||||
import email_validator
|
||||
@@ -343,6 +344,35 @@ class Tag(BaseModel):
|
||||
externalDocs: Optional[ExternalDocumentation] = None
|
||||
|
||||
|
||||
class BaseAdditionalResponse(BaseModel):
|
||||
description: str
|
||||
content_type: str = None
|
||||
|
||||
|
||||
class AdditionalResponse(BaseAdditionalResponse):
|
||||
status_code: int = PSchema(
|
||||
...,
|
||||
ge=100,
|
||||
le=540,
|
||||
title='Status Code',
|
||||
description='HTTP status code',
|
||||
)
|
||||
# NOTE: waiting for pydantic to allow `typing.Type[BasicModel]` type
|
||||
# so, going for `Any` and extra validation on
|
||||
# routing methods
|
||||
models: Optional[List[Any]] = PSchema(
|
||||
[],
|
||||
title='Additional Response Models',
|
||||
)
|
||||
|
||||
|
||||
class AdditionalResponseDescription(BaseAdditionalResponse):
|
||||
schema_field: Optional[Field] = None
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
|
||||
class OpenAPI(BaseModel):
|
||||
openapi: str
|
||||
info: Info
|
||||
|
||||
@@ -205,6 +205,26 @@ def get_openapi_path(
|
||||
}
|
||||
},
|
||||
}
|
||||
for add_response_code, add_response in route.additional_responses.items():
|
||||
add_response_schema = {}
|
||||
if (add_response.content_type or route.content_type.media_type
|
||||
) == 'application/json' and add_response.schema_field is not None:
|
||||
add_response_schema, _ = field_schema(
|
||||
add_response.schema_field,
|
||||
model_name_map=model_name_map,
|
||||
ref_prefix=REF_PREFIX,
|
||||
)
|
||||
add_content = {
|
||||
add_response.content_type or
|
||||
route.content_type.media_type: {
|
||||
"schema": add_response_schema,
|
||||
},
|
||||
}
|
||||
operation["responses"][str(add_response_code)] = \
|
||||
{
|
||||
"description": add_response.description,
|
||||
"content": add_content,
|
||||
}
|
||||
path[method.lower()] = operation
|
||||
return path, security_schemes, definitions
|
||||
|
||||
|
||||
Reference in New Issue
Block a user