2019-06-18 15:46:57 +08:00
|
|
|
import http.client
|
2021-07-03 21:51:28 +02:00
|
|
|
import inspect
|
2022-03-04 14:02:18 -08:00
|
|
|
import warnings
|
2020-05-23 18:56:18 +02:00
|
|
|
from enum import Enum
|
|
|
|
|
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast
|
2018-12-06 23:47:58 +04:00
|
|
|
|
2018-12-06 20:24:50 +04:00
|
|
|
from fastapi import routing
|
✨ Add support for shared/top-level parameters (dependencies, tags, etc) (#2434)
* ✨ Add Default and DefaultPlaceholder data structures
to handle defaults and overrides
* ✨ Add utils to get values by priority handling DefaultPlaceholders
* ✨ Add support for top-level parameters in FastAPI, APIRouter, include_router
including: prefix, tags, dependencies, deprecated, include_in_schema, responses, default_response_class, callbacks
* ♻️ Update openapi utils to handle DefaultPlaceholder for response_class
* 📝 Update bigger-application example code to use top-level params
and showcase them in APIRouter, FastAPI, include_router
* 📝 Update docs for Bigger Applications, include diagrams, top-level params
* 🔥 Simplify code and docs for callbacks as default_response_class is no longer required
* 📝 Add docs for top-level dependencies, in FastAPI()
* 📝 Add docs reference to top-level dependencies in docs for decorator
* ✅ Update/increase tests for Bigger Applications including shared parameters
* ✅ Add tests for top-level dependencies in FastAPI()
* ✅ Add tests for internal DefaultPlaceholder
* ✅ Update/increase tests for callbacks with top-level parameters
* ✅ Add LOTS of tests covering branches and cases for shared parameters
in top-level FastAPI, path operations, include_router, APIRouter, its path operations, nested include_router, nested APIRouter, and its path operations
* 🎨 Format/reorder parameters for consistency in FastAPI, APIRouter, include_router
2020-11-29 18:32:18 +01:00
|
|
|
from fastapi.datastructures import DefaultPlaceholder
|
2018-12-06 20:24:50 +04:00
|
|
|
from fastapi.dependencies.models import Dependant
|
2020-05-23 18:56:18 +02:00
|
|
|
from fastapi.dependencies.utils import get_flat_dependant, get_flat_params
|
2018-12-06 20:24:50 +04:00
|
|
|
from fastapi.encoders import jsonable_encoder
|
2022-07-14 13:19:42 +02:00
|
|
|
from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX
|
2018-12-06 20:24:50 +04:00
|
|
|
from fastapi.openapi.models import OpenAPI
|
2018-12-07 19:12:16 +04:00
|
|
|
from fastapi.params import Body, Param
|
2020-12-20 19:50:00 +01:00
|
|
|
from fastapi.responses import Response
|
2019-06-28 19:35:16 +02:00
|
|
|
from fastapi.utils import (
|
2020-06-15 13:12:12 +02:00
|
|
|
deep_dict_update,
|
2019-06-28 19:35:16 +02:00
|
|
|
generate_operation_id_for_path,
|
|
|
|
|
get_model_definitions,
|
2022-07-14 13:19:42 +02:00
|
|
|
is_body_allowed_for_status_code,
|
2019-06-28 19:35:16 +02:00
|
|
|
)
|
2019-11-27 11:32:02 -08:00
|
|
|
from pydantic import BaseModel
|
2021-05-05 11:20:56 -07:00
|
|
|
from pydantic.fields import ModelField, Undefined
|
2020-05-23 18:56:18 +02:00
|
|
|
from pydantic.schema import (
|
|
|
|
|
field_schema,
|
|
|
|
|
get_flat_models_from_fields,
|
|
|
|
|
get_model_name_map,
|
|
|
|
|
)
|
2018-12-18 22:36:04 +04:00
|
|
|
from pydantic.utils import lenient_issubclass
|
|
|
|
|
from starlette.responses import JSONResponse
|
|
|
|
|
from starlette.routing import BaseRoute
|
|
|
|
|
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
|
2018-12-06 23:47:58 +04:00
|
|
|
|
2018-12-06 20:24:50 +04:00
|
|
|
validation_error_definition = {
|
|
|
|
|
"title": "ValidationError",
|
|
|
|
|
"type": "object",
|
|
|
|
|
"properties": {
|
2022-04-17 12:41:46 -05:00
|
|
|
"loc": {
|
|
|
|
|
"title": "Location",
|
|
|
|
|
"type": "array",
|
|
|
|
|
"items": {"anyOf": [{"type": "string"}, {"type": "integer"}]},
|
|
|
|
|
},
|
2018-12-06 20:24:50 +04:00
|
|
|
"msg": {"title": "Message", "type": "string"},
|
|
|
|
|
"type": {"title": "Error Type", "type": "string"},
|
|
|
|
|
},
|
|
|
|
|
"required": ["loc", "msg", "type"],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
validation_error_response_definition = {
|
|
|
|
|
"title": "HTTPValidationError",
|
|
|
|
|
"type": "object",
|
|
|
|
|
"properties": {
|
|
|
|
|
"detail": {
|
|
|
|
|
"title": "Detail",
|
|
|
|
|
"type": "array",
|
|
|
|
|
"items": {"$ref": REF_PREFIX + "ValidationError"},
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
2019-08-30 19:17:42 +03:00
|
|
|
status_code_ranges: Dict[str, str] = {
|
|
|
|
|
"1XX": "Information",
|
|
|
|
|
"2XX": "Success",
|
|
|
|
|
"3XX": "Redirection",
|
|
|
|
|
"4XX": "Client Error",
|
|
|
|
|
"5XX": "Server Error",
|
2019-08-30 16:34:47 -05:00
|
|
|
"DEFAULT": "Default Response",
|
2019-08-30 19:17:42 +03:00
|
|
|
}
|
|
|
|
|
|
2018-12-06 20:24:50 +04:00
|
|
|
|
2020-12-20 19:50:00 +01:00
|
|
|
def get_openapi_security_definitions(
|
|
|
|
|
flat_dependant: Dependant,
|
|
|
|
|
) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
|
2018-12-06 23:47:58 +04:00
|
|
|
security_definitions = {}
|
|
|
|
|
operation_security = []
|
|
|
|
|
for security_requirement in flat_dependant.security_requirements:
|
|
|
|
|
security_definition = jsonable_encoder(
|
|
|
|
|
security_requirement.security_scheme.model,
|
|
|
|
|
by_alias=True,
|
2020-04-05 15:04:46 +02:00
|
|
|
exclude_none=True,
|
2018-12-06 23:47:58 +04:00
|
|
|
)
|
2018-12-07 19:12:16 +04:00
|
|
|
security_name = security_requirement.security_scheme.scheme_name
|
2018-12-06 23:47:58 +04:00
|
|
|
security_definitions[security_name] = security_definition
|
|
|
|
|
operation_security.append({security_name: security_requirement.scopes})
|
|
|
|
|
return security_definitions, operation_security
|
|
|
|
|
|
|
|
|
|
|
2018-12-07 19:12:16 +04:00
|
|
|
def get_openapi_operation_parameters(
|
2020-05-23 18:56:18 +02:00
|
|
|
*,
|
2019-11-27 11:32:02 -08:00
|
|
|
all_route_params: Sequence[ModelField],
|
2020-06-14 15:38:29 +02:00
|
|
|
model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
|
2019-08-31 00:46:05 +03:00
|
|
|
) -> List[Dict[str, Any]]:
|
2018-12-06 23:47:58 +04:00
|
|
|
parameters = []
|
|
|
|
|
for param in all_route_params:
|
2020-08-09 22:17:08 +02:00
|
|
|
field_info = param.field_info
|
2019-11-27 11:32:02 -08:00
|
|
|
field_info = cast(Param, field_info)
|
2022-01-23 23:54:59 +08:00
|
|
|
if not field_info.include_in_schema:
|
|
|
|
|
continue
|
2018-12-06 23:47:58 +04:00
|
|
|
parameter = {
|
|
|
|
|
"name": param.alias,
|
2019-11-27 11:32:02 -08:00
|
|
|
"in": field_info.in_.value,
|
2018-12-06 23:47:58 +04:00
|
|
|
"required": param.required,
|
2020-05-23 18:56:18 +02:00
|
|
|
"schema": field_schema(
|
2020-12-20 19:50:00 +01:00
|
|
|
param, model_name_map=model_name_map, ref_prefix=REF_PREFIX
|
2020-05-23 18:56:18 +02:00
|
|
|
)[0],
|
2018-12-06 23:47:58 +04:00
|
|
|
}
|
2019-11-27 11:32:02 -08:00
|
|
|
if field_info.description:
|
|
|
|
|
parameter["description"] = field_info.description
|
2021-05-05 11:20:56 -07:00
|
|
|
if field_info.examples:
|
|
|
|
|
parameter["examples"] = jsonable_encoder(field_info.examples)
|
|
|
|
|
elif field_info.example != Undefined:
|
|
|
|
|
parameter["example"] = jsonable_encoder(field_info.example)
|
2019-11-27 11:32:02 -08:00
|
|
|
if field_info.deprecated:
|
|
|
|
|
parameter["deprecated"] = field_info.deprecated
|
2018-12-06 23:47:58 +04:00
|
|
|
parameters.append(parameter)
|
2019-08-31 00:46:05 +03:00
|
|
|
return parameters
|
2018-12-06 23:47:58 +04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_openapi_operation_request_body(
|
2020-05-23 18:56:18 +02:00
|
|
|
*,
|
|
|
|
|
body_field: Optional[ModelField],
|
2020-06-14 15:38:29 +02:00
|
|
|
model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
|
2020-12-20 19:50:00 +01:00
|
|
|
) -> Optional[Dict[str, Any]]:
|
2018-12-06 23:47:58 +04:00
|
|
|
if not body_field:
|
|
|
|
|
return None
|
2019-11-27 11:32:02 -08:00
|
|
|
assert isinstance(body_field, ModelField)
|
2019-07-12 16:56:25 -07:00
|
|
|
body_schema, _, _ = field_schema(
|
2020-12-20 19:50:00 +01:00
|
|
|
body_field, model_name_map=model_name_map, ref_prefix=REF_PREFIX
|
2018-12-06 23:47:58 +04:00
|
|
|
)
|
2020-08-09 22:17:08 +02:00
|
|
|
field_info = cast(Body, body_field.field_info)
|
2019-11-27 11:32:02 -08:00
|
|
|
request_media_type = field_info.media_type
|
2018-12-06 23:47:58 +04:00
|
|
|
required = body_field.required
|
2018-12-07 19:12:16 +04:00
|
|
|
request_body_oai: Dict[str, Any] = {}
|
2018-12-06 23:47:58 +04:00
|
|
|
if required:
|
|
|
|
|
request_body_oai["required"] = required
|
2021-05-05 11:20:56 -07:00
|
|
|
request_media_content: Dict[str, Any] = {"schema": body_schema}
|
|
|
|
|
if field_info.examples:
|
|
|
|
|
request_media_content["examples"] = jsonable_encoder(field_info.examples)
|
|
|
|
|
elif field_info.example != Undefined:
|
|
|
|
|
request_media_content["example"] = jsonable_encoder(field_info.example)
|
|
|
|
|
request_body_oai["content"] = {request_media_type: request_media_content}
|
2018-12-06 23:47:58 +04:00
|
|
|
return request_body_oai
|
|
|
|
|
|
|
|
|
|
|
2022-03-04 14:02:18 -08:00
|
|
|
def generate_operation_id(
|
|
|
|
|
*, route: routing.APIRoute, method: str
|
|
|
|
|
) -> str: # pragma: nocover
|
|
|
|
|
warnings.warn(
|
|
|
|
|
"fastapi.openapi.utils.generate_operation_id() was deprecated, "
|
|
|
|
|
"it is not used internally, and will be removed soon",
|
|
|
|
|
DeprecationWarning,
|
|
|
|
|
stacklevel=2,
|
|
|
|
|
)
|
2018-12-06 23:47:58 +04:00
|
|
|
if route.operation_id:
|
|
|
|
|
return route.operation_id
|
2019-05-16 15:55:14 +02:00
|
|
|
path: str = route.path_format
|
2019-06-28 19:35:16 +02:00
|
|
|
return generate_operation_id_for_path(name=route.name, path=path, method=method)
|
2018-12-06 23:47:58 +04:00
|
|
|
|
|
|
|
|
|
2018-12-07 19:12:16 +04:00
|
|
|
def generate_operation_summary(*, route: routing.APIRoute, method: str) -> str:
|
2018-12-06 23:47:58 +04:00
|
|
|
if route.summary:
|
|
|
|
|
return route.summary
|
2019-04-12 21:25:26 +04:00
|
|
|
return route.name.replace("_", " ").title()
|
2018-12-06 23:47:58 +04:00
|
|
|
|
2018-12-07 19:12:16 +04:00
|
|
|
|
2020-12-20 19:50:00 +01:00
|
|
|
def get_openapi_operation_metadata(
|
2022-03-04 14:02:18 -08:00
|
|
|
*, route: routing.APIRoute, method: str, operation_ids: Set[str]
|
2020-12-20 19:50:00 +01:00
|
|
|
) -> Dict[str, Any]:
|
2018-12-06 23:47:58 +04:00
|
|
|
operation: Dict[str, Any] = {}
|
|
|
|
|
if route.tags:
|
|
|
|
|
operation["tags"] = route.tags
|
|
|
|
|
operation["summary"] = generate_operation_summary(route=route, method=method)
|
|
|
|
|
if route.description:
|
|
|
|
|
operation["description"] = route.description
|
2022-03-04 14:02:18 -08:00
|
|
|
operation_id = route.operation_id or route.unique_id
|
|
|
|
|
if operation_id in operation_ids:
|
|
|
|
|
message = (
|
|
|
|
|
f"Duplicate Operation ID {operation_id} for function "
|
|
|
|
|
+ f"{route.endpoint.__name__}"
|
|
|
|
|
)
|
|
|
|
|
file_name = getattr(route.endpoint, "__globals__", {}).get("__file__")
|
|
|
|
|
if file_name:
|
|
|
|
|
message += f" at {file_name}"
|
|
|
|
|
warnings.warn(message)
|
|
|
|
|
operation_ids.add(operation_id)
|
|
|
|
|
operation["operationId"] = operation_id
|
2018-12-06 23:47:58 +04:00
|
|
|
if route.deprecated:
|
|
|
|
|
operation["deprecated"] = route.deprecated
|
|
|
|
|
return operation
|
|
|
|
|
|
|
|
|
|
|
2018-12-07 19:12:16 +04:00
|
|
|
def get_openapi_path(
|
2022-03-04 14:02:18 -08:00
|
|
|
*, route: routing.APIRoute, model_name_map: Dict[type, str], operation_ids: Set[str]
|
2020-12-20 19:50:00 +01:00
|
|
|
) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
|
2018-12-06 20:24:50 +04:00
|
|
|
path = {}
|
2018-12-06 23:47:58 +04:00
|
|
|
security_schemes: Dict[str, Any] = {}
|
|
|
|
|
definitions: Dict[str, Any] = {}
|
2018-12-07 19:12:16 +04:00
|
|
|
assert route.methods is not None, "Methods must be a list"
|
✨ Add support for shared/top-level parameters (dependencies, tags, etc) (#2434)
* ✨ Add Default and DefaultPlaceholder data structures
to handle defaults and overrides
* ✨ Add utils to get values by priority handling DefaultPlaceholders
* ✨ Add support for top-level parameters in FastAPI, APIRouter, include_router
including: prefix, tags, dependencies, deprecated, include_in_schema, responses, default_response_class, callbacks
* ♻️ Update openapi utils to handle DefaultPlaceholder for response_class
* 📝 Update bigger-application example code to use top-level params
and showcase them in APIRouter, FastAPI, include_router
* 📝 Update docs for Bigger Applications, include diagrams, top-level params
* 🔥 Simplify code and docs for callbacks as default_response_class is no longer required
* 📝 Add docs for top-level dependencies, in FastAPI()
* 📝 Add docs reference to top-level dependencies in docs for decorator
* ✅ Update/increase tests for Bigger Applications including shared parameters
* ✅ Add tests for top-level dependencies in FastAPI()
* ✅ Add tests for internal DefaultPlaceholder
* ✅ Update/increase tests for callbacks with top-level parameters
* ✅ Add LOTS of tests covering branches and cases for shared parameters
in top-level FastAPI, path operations, include_router, APIRouter, its path operations, nested include_router, nested APIRouter, and its path operations
* 🎨 Format/reorder parameters for consistency in FastAPI, APIRouter, include_router
2020-11-29 18:32:18 +01:00
|
|
|
if isinstance(route.response_class, DefaultPlaceholder):
|
2020-12-20 19:50:00 +01:00
|
|
|
current_response_class: Type[Response] = route.response_class.value
|
✨ Add support for shared/top-level parameters (dependencies, tags, etc) (#2434)
* ✨ Add Default and DefaultPlaceholder data structures
to handle defaults and overrides
* ✨ Add utils to get values by priority handling DefaultPlaceholders
* ✨ Add support for top-level parameters in FastAPI, APIRouter, include_router
including: prefix, tags, dependencies, deprecated, include_in_schema, responses, default_response_class, callbacks
* ♻️ Update openapi utils to handle DefaultPlaceholder for response_class
* 📝 Update bigger-application example code to use top-level params
and showcase them in APIRouter, FastAPI, include_router
* 📝 Update docs for Bigger Applications, include diagrams, top-level params
* 🔥 Simplify code and docs for callbacks as default_response_class is no longer required
* 📝 Add docs for top-level dependencies, in FastAPI()
* 📝 Add docs reference to top-level dependencies in docs for decorator
* ✅ Update/increase tests for Bigger Applications including shared parameters
* ✅ Add tests for top-level dependencies in FastAPI()
* ✅ Add tests for internal DefaultPlaceholder
* ✅ Update/increase tests for callbacks with top-level parameters
* ✅ Add LOTS of tests covering branches and cases for shared parameters
in top-level FastAPI, path operations, include_router, APIRouter, its path operations, nested include_router, nested APIRouter, and its path operations
* 🎨 Format/reorder parameters for consistency in FastAPI, APIRouter, include_router
2020-11-29 18:32:18 +01:00
|
|
|
else:
|
|
|
|
|
current_response_class = route.response_class
|
|
|
|
|
assert current_response_class, "A response class is needed to generate OpenAPI"
|
|
|
|
|
route_response_media_type: Optional[str] = current_response_class.media_type
|
2018-12-28 16:10:29 +04:00
|
|
|
if route.include_in_schema:
|
|
|
|
|
for method in route.methods:
|
2022-03-04 14:02:18 -08:00
|
|
|
operation = get_openapi_operation_metadata(
|
|
|
|
|
route=route, method=method, operation_ids=operation_ids
|
|
|
|
|
)
|
2020-12-20 19:50:00 +01:00
|
|
|
parameters: List[Dict[str, Any]] = []
|
2019-08-24 19:55:25 -07:00
|
|
|
flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True)
|
2018-12-28 16:10:29 +04:00
|
|
|
security_definitions, operation_security = get_openapi_security_definitions(
|
|
|
|
|
flat_dependant=flat_dependant
|
2018-12-06 23:47:58 +04:00
|
|
|
)
|
2018-12-28 16:10:29 +04:00
|
|
|
if operation_security:
|
|
|
|
|
operation.setdefault("security", []).extend(operation_security)
|
|
|
|
|
if security_definitions:
|
|
|
|
|
security_schemes.update(security_definitions)
|
2020-05-23 18:56:18 +02:00
|
|
|
all_route_params = get_flat_params(route.dependant)
|
|
|
|
|
operation_parameters = get_openapi_operation_parameters(
|
|
|
|
|
all_route_params=all_route_params, model_name_map=model_name_map
|
|
|
|
|
)
|
2018-12-28 16:10:29 +04:00
|
|
|
parameters.extend(operation_parameters)
|
|
|
|
|
if parameters:
|
2022-09-03 13:12:41 -04:00
|
|
|
all_parameters = {
|
|
|
|
|
(param["in"], param["name"]): param for param in parameters
|
|
|
|
|
}
|
|
|
|
|
required_parameters = {
|
|
|
|
|
(param["in"], param["name"]): param
|
|
|
|
|
for param in parameters
|
|
|
|
|
if param.get("required")
|
|
|
|
|
}
|
|
|
|
|
# Make sure required definitions of the same parameter take precedence
|
|
|
|
|
# over non-required definitions
|
|
|
|
|
all_parameters.update(required_parameters)
|
|
|
|
|
operation["parameters"] = list(all_parameters.values())
|
2018-12-28 16:10:29 +04:00
|
|
|
if method in METHODS_WITH_BODY:
|
|
|
|
|
request_body_oai = get_openapi_operation_request_body(
|
|
|
|
|
body_field=route.body_field, model_name_map=model_name_map
|
2018-12-06 20:24:50 +04:00
|
|
|
)
|
2018-12-28 16:10:29 +04:00
|
|
|
if request_body_oai:
|
|
|
|
|
operation["requestBody"] = request_body_oai
|
2019-12-11 18:58:01 +02:00
|
|
|
if route.callbacks:
|
|
|
|
|
callbacks = {}
|
|
|
|
|
for callback in route.callbacks:
|
2020-12-20 19:50:00 +01:00
|
|
|
if isinstance(callback, routing.APIRoute):
|
|
|
|
|
(
|
|
|
|
|
cb_path,
|
|
|
|
|
cb_security_schemes,
|
|
|
|
|
cb_definitions,
|
|
|
|
|
) = get_openapi_path(
|
2022-03-04 14:02:18 -08:00
|
|
|
route=callback,
|
|
|
|
|
model_name_map=model_name_map,
|
|
|
|
|
operation_ids=operation_ids,
|
2020-12-20 19:50:00 +01:00
|
|
|
)
|
|
|
|
|
callbacks[callback.name] = {callback.path: cb_path}
|
2019-12-11 18:58:01 +02:00
|
|
|
operation["callbacks"] = callbacks
|
2021-07-03 21:51:28 +02:00
|
|
|
if route.status_code is not None:
|
|
|
|
|
status_code = str(route.status_code)
|
|
|
|
|
else:
|
|
|
|
|
# It would probably make more sense for all response classes to have an
|
|
|
|
|
# explicit default status_code, and to extract it from them, instead of
|
|
|
|
|
# doing this inspection tricks, that would probably be in the future
|
|
|
|
|
# TODO: probably make status_code a default class attribute for all
|
|
|
|
|
# responses in Starlette
|
|
|
|
|
response_signature = inspect.signature(current_response_class.__init__)
|
|
|
|
|
status_code_param = response_signature.parameters.get("status_code")
|
|
|
|
|
if status_code_param is not None:
|
|
|
|
|
if isinstance(status_code_param.default, int):
|
|
|
|
|
status_code = str(status_code_param.default)
|
2019-04-05 13:54:00 +04:00
|
|
|
operation.setdefault("responses", {}).setdefault(status_code, {})[
|
|
|
|
|
"description"
|
|
|
|
|
] = route.response_description
|
2022-07-14 13:19:42 +02:00
|
|
|
if route_response_media_type and is_body_allowed_for_status_code(
|
|
|
|
|
route.status_code
|
2019-11-24 05:15:39 -08:00
|
|
|
):
|
|
|
|
|
response_schema = {"type": "string"}
|
✨ Add support for shared/top-level parameters (dependencies, tags, etc) (#2434)
* ✨ Add Default and DefaultPlaceholder data structures
to handle defaults and overrides
* ✨ Add utils to get values by priority handling DefaultPlaceholders
* ✨ Add support for top-level parameters in FastAPI, APIRouter, include_router
including: prefix, tags, dependencies, deprecated, include_in_schema, responses, default_response_class, callbacks
* ♻️ Update openapi utils to handle DefaultPlaceholder for response_class
* 📝 Update bigger-application example code to use top-level params
and showcase them in APIRouter, FastAPI, include_router
* 📝 Update docs for Bigger Applications, include diagrams, top-level params
* 🔥 Simplify code and docs for callbacks as default_response_class is no longer required
* 📝 Add docs for top-level dependencies, in FastAPI()
* 📝 Add docs reference to top-level dependencies in docs for decorator
* ✅ Update/increase tests for Bigger Applications including shared parameters
* ✅ Add tests for top-level dependencies in FastAPI()
* ✅ Add tests for internal DefaultPlaceholder
* ✅ Update/increase tests for callbacks with top-level parameters
* ✅ Add LOTS of tests covering branches and cases for shared parameters
in top-level FastAPI, path operations, include_router, APIRouter, its path operations, nested include_router, nested APIRouter, and its path operations
* 🎨 Format/reorder parameters for consistency in FastAPI, APIRouter, include_router
2020-11-29 18:32:18 +01:00
|
|
|
if lenient_issubclass(current_response_class, JSONResponse):
|
2019-11-24 05:15:39 -08:00
|
|
|
if route.response_field:
|
|
|
|
|
response_schema, _, _ = field_schema(
|
|
|
|
|
route.response_field,
|
|
|
|
|
model_name_map=model_name_map,
|
|
|
|
|
ref_prefix=REF_PREFIX,
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
response_schema = {}
|
|
|
|
|
operation.setdefault("responses", {}).setdefault(
|
|
|
|
|
status_code, {}
|
|
|
|
|
).setdefault("content", {}).setdefault(route_response_media_type, {})[
|
|
|
|
|
"schema"
|
|
|
|
|
] = response_schema
|
2020-06-15 13:12:12 +02:00
|
|
|
if route.responses:
|
|
|
|
|
operation_responses = operation.setdefault("responses", {})
|
|
|
|
|
for (
|
|
|
|
|
additional_status_code,
|
|
|
|
|
additional_response,
|
|
|
|
|
) in route.responses.items():
|
|
|
|
|
process_response = additional_response.copy()
|
|
|
|
|
process_response.pop("model", None)
|
|
|
|
|
status_code_key = str(additional_status_code).upper()
|
|
|
|
|
if status_code_key == "DEFAULT":
|
|
|
|
|
status_code_key = "default"
|
|
|
|
|
openapi_response = operation_responses.setdefault(
|
|
|
|
|
status_code_key, {}
|
|
|
|
|
)
|
|
|
|
|
assert isinstance(
|
|
|
|
|
process_response, dict
|
|
|
|
|
), "An additional response must be a dict"
|
|
|
|
|
field = route.response_fields.get(additional_status_code)
|
|
|
|
|
additional_field_schema: Optional[Dict[str, Any]] = None
|
|
|
|
|
if field:
|
|
|
|
|
additional_field_schema, _, _ = field_schema(
|
|
|
|
|
field, model_name_map=model_name_map, ref_prefix=REF_PREFIX
|
|
|
|
|
)
|
|
|
|
|
media_type = route_response_media_type or "application/json"
|
|
|
|
|
additional_schema = (
|
|
|
|
|
process_response.setdefault("content", {})
|
|
|
|
|
.setdefault(media_type, {})
|
|
|
|
|
.setdefault("schema", {})
|
|
|
|
|
)
|
|
|
|
|
deep_dict_update(additional_schema, additional_field_schema)
|
|
|
|
|
status_text: Optional[str] = status_code_ranges.get(
|
|
|
|
|
str(additional_status_code).upper()
|
|
|
|
|
) or http.client.responses.get(int(additional_status_code))
|
|
|
|
|
description = (
|
|
|
|
|
process_response.get("description")
|
|
|
|
|
or openapi_response.get("description")
|
|
|
|
|
or status_text
|
|
|
|
|
or "Additional Response"
|
|
|
|
|
)
|
|
|
|
|
deep_dict_update(openapi_response, process_response)
|
|
|
|
|
openapi_response["description"] = description
|
2019-08-31 00:46:05 +03:00
|
|
|
http422 = str(HTTP_422_UNPROCESSABLE_ENTITY)
|
|
|
|
|
if (all_route_params or route.body_field) and not any(
|
|
|
|
|
[
|
|
|
|
|
status in operation["responses"]
|
2019-10-04 03:08:29 +03:00
|
|
|
for status in [http422, "4XX", "default"]
|
2019-08-31 00:46:05 +03:00
|
|
|
]
|
|
|
|
|
):
|
|
|
|
|
operation["responses"][http422] = {
|
2018-12-28 16:10:29 +04:00
|
|
|
"description": "Validation Error",
|
|
|
|
|
"content": {
|
|
|
|
|
"application/json": {
|
|
|
|
|
"schema": {"$ref": REF_PREFIX + "HTTPValidationError"}
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
}
|
2019-08-31 00:46:05 +03:00
|
|
|
if "ValidationError" not in definitions:
|
|
|
|
|
definitions.update(
|
|
|
|
|
{
|
|
|
|
|
"ValidationError": validation_error_definition,
|
|
|
|
|
"HTTPValidationError": validation_error_response_definition,
|
|
|
|
|
}
|
|
|
|
|
)
|
2021-07-29 16:01:13 -04:00
|
|
|
if route.openapi_extra:
|
|
|
|
|
deep_dict_update(operation, route.openapi_extra)
|
2018-12-28 16:10:29 +04:00
|
|
|
path[method.lower()] = operation
|
2018-12-06 20:24:50 +04:00
|
|
|
return path, security_schemes, definitions
|
|
|
|
|
|
|
|
|
|
|
2020-05-23 18:56:18 +02:00
|
|
|
def get_flat_models_from_routes(
|
|
|
|
|
routes: Sequence[BaseRoute],
|
|
|
|
|
) -> Set[Union[Type[BaseModel], Type[Enum]]]:
|
|
|
|
|
body_fields_from_routes: List[ModelField] = []
|
|
|
|
|
responses_from_routes: List[ModelField] = []
|
|
|
|
|
request_fields_from_routes: List[ModelField] = []
|
|
|
|
|
callback_flat_models: Set[Union[Type[BaseModel], Type[Enum]]] = set()
|
|
|
|
|
for route in routes:
|
|
|
|
|
if getattr(route, "include_in_schema", None) and isinstance(
|
|
|
|
|
route, routing.APIRoute
|
|
|
|
|
):
|
|
|
|
|
if route.body_field:
|
|
|
|
|
assert isinstance(
|
|
|
|
|
route.body_field, ModelField
|
|
|
|
|
), "A request body must be a Pydantic Field"
|
|
|
|
|
body_fields_from_routes.append(route.body_field)
|
|
|
|
|
if route.response_field:
|
|
|
|
|
responses_from_routes.append(route.response_field)
|
|
|
|
|
if route.response_fields:
|
|
|
|
|
responses_from_routes.extend(route.response_fields.values())
|
|
|
|
|
if route.callbacks:
|
|
|
|
|
callback_flat_models |= get_flat_models_from_routes(route.callbacks)
|
|
|
|
|
params = get_flat_params(route.dependant)
|
|
|
|
|
request_fields_from_routes.extend(params)
|
|
|
|
|
|
|
|
|
|
flat_models = callback_flat_models | get_flat_models_from_fields(
|
|
|
|
|
body_fields_from_routes + responses_from_routes + request_fields_from_routes,
|
|
|
|
|
known_models=set(),
|
|
|
|
|
)
|
|
|
|
|
return flat_models
|
|
|
|
|
|
|
|
|
|
|
2018-12-06 20:24:50 +04:00
|
|
|
def get_openapi(
|
|
|
|
|
*,
|
|
|
|
|
title: str,
|
|
|
|
|
version: str,
|
|
|
|
|
openapi_version: str = "3.0.2",
|
2020-08-03 16:59:07 +04:30
|
|
|
description: Optional[str] = None,
|
2019-02-14 10:57:49 -08:00
|
|
|
routes: Sequence[BaseRoute],
|
2020-06-14 15:38:29 +02:00
|
|
|
tags: Optional[List[Dict[str, Any]]] = None,
|
|
|
|
|
servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
|
2021-07-29 15:10:22 +00:00
|
|
|
terms_of_service: Optional[str] = None,
|
|
|
|
|
contact: Optional[Dict[str, Union[str, Any]]] = None,
|
|
|
|
|
license_info: Optional[Dict[str, Union[str, Any]]] = None,
|
2020-12-20 19:50:00 +01:00
|
|
|
) -> Dict[str, Any]:
|
2021-07-29 15:10:22 +00:00
|
|
|
info: Dict[str, Any] = {"title": title, "version": version}
|
2018-12-06 20:24:50 +04:00
|
|
|
if description:
|
|
|
|
|
info["description"] = description
|
2021-07-29 15:10:22 +00:00
|
|
|
if terms_of_service:
|
|
|
|
|
info["termsOfService"] = terms_of_service
|
|
|
|
|
if contact:
|
|
|
|
|
info["contact"] = contact
|
|
|
|
|
if license_info:
|
|
|
|
|
info["license"] = license_info
|
2020-06-13 07:58:06 -04:00
|
|
|
output: Dict[str, Any] = {"openapi": openapi_version, "info": info}
|
2020-06-14 15:38:29 +02:00
|
|
|
if servers:
|
|
|
|
|
output["servers"] = servers
|
2020-12-20 19:50:00 +01:00
|
|
|
components: Dict[str, Dict[str, Any]] = {}
|
|
|
|
|
paths: Dict[str, Dict[str, Any]] = {}
|
2022-03-04 14:02:18 -08:00
|
|
|
operation_ids: Set[str] = set()
|
2018-12-06 20:24:50 +04:00
|
|
|
flat_models = get_flat_models_from_routes(routes)
|
2020-12-20 19:50:00 +01:00
|
|
|
model_name_map = get_model_name_map(flat_models)
|
2018-12-06 20:24:50 +04:00
|
|
|
definitions = get_model_definitions(
|
2020-12-20 19:50:00 +01:00
|
|
|
flat_models=flat_models, model_name_map=model_name_map
|
2018-12-06 20:24:50 +04:00
|
|
|
)
|
|
|
|
|
for route in routes:
|
2018-12-07 19:12:16 +04:00
|
|
|
if isinstance(route, routing.APIRoute):
|
2022-03-04 14:02:18 -08:00
|
|
|
result = get_openapi_path(
|
|
|
|
|
route=route, model_name_map=model_name_map, operation_ids=operation_ids
|
|
|
|
|
)
|
2018-12-07 19:12:16 +04:00
|
|
|
if result:
|
|
|
|
|
path, security_schemes, path_definitions = result
|
|
|
|
|
if path:
|
2020-07-10 13:28:18 -04:00
|
|
|
paths.setdefault(route.path_format, {}).update(path)
|
2018-12-07 19:12:16 +04:00
|
|
|
if security_schemes:
|
|
|
|
|
components.setdefault("securitySchemes", {}).update(
|
|
|
|
|
security_schemes
|
|
|
|
|
)
|
|
|
|
|
if path_definitions:
|
|
|
|
|
definitions.update(path_definitions)
|
2018-12-06 20:24:50 +04:00
|
|
|
if definitions:
|
2019-10-04 13:08:41 -07:00
|
|
|
components["schemas"] = {k: definitions[k] for k in sorted(definitions)}
|
2018-12-06 20:24:50 +04:00
|
|
|
if components:
|
|
|
|
|
output["components"] = components
|
|
|
|
|
output["paths"] = paths
|
2020-06-13 07:58:06 -04:00
|
|
|
if tags:
|
|
|
|
|
output["tags"] = tags
|
2020-12-20 19:50:00 +01:00
|
|
|
return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore
|