Skip to content

OpenAPI

MODULE DESCRIPTION
dependant
encoders
exceptions
models
params
swagger_ui

dependant

FUNCTION DESCRIPTION
add_param_to_fields

Adds a parameter to the list of parameters in the dependant model.

get_body_field

Get the Body field for a given Dependant object.

get_body_field_info

Get the Body field info and kwargs for a given body model.

get_dependant

Returns a dependant model for a handler function. A dependant model is a model that contains

get_flat_params

Get a list of all the parameters from a Dependant object.

get_path_param_names

Returns the path parameter names from a path template. Those are the strings between { and }.

get_typed_annotation

Evaluates a type annotation, which can be a string or a ForwardRef.

get_typed_signature

Returns a typed signature for a callable, resolving forward references.

is_body_param

Returns whether a parameter is a request body parameter, by checking if it is a scalar field or a body field.

add_param_to_fields

add_param_to_fields(
    *, field: ModelField, dependant: Dependant
) -> None

Adds a parameter to the list of parameters in the dependant model.

PARAMETER DESCRIPTION
field

The field to add

TYPE: ModelField

dependant

The dependant model to add the field to

TYPE: Dependant

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def add_param_to_fields(
    *,
    field: ModelField,
    dependant: Dependant,
) -> None:
    """
    Adds a parameter to the list of parameters in the dependant model.

    Parameters
    ----------
    field: ModelField
        The field to add
    dependant: Dependant
        The dependant model to add the field to

    """
    field_info = cast(Param, field.field_info)

    # Dictionary to map ParamTypes to their corresponding lists in dependant
    param_type_map = {
        ParamTypes.path: dependant.path_params,
        ParamTypes.query: dependant.query_params,
        ParamTypes.header: dependant.header_params,
        ParamTypes.cookie: dependant.cookie_params,
    }

    # Check if field_info.in_ is a valid key in param_type_map and append the field to the corresponding list
    # or raise an exception if it's not a valid key.
    if field_info.in_ in param_type_map:
        param_type_map[field_info.in_].append(field)
    else:
        raise AssertionError(f"Unsupported param type: {field_info.in_}")

get_body_field

get_body_field(
    *, dependant: Dependant, name: str
) -> ModelField | None

Get the Body field for a given Dependant object.

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def get_body_field(*, dependant: Dependant, name: str) -> ModelField | None:
    """
    Get the Body field for a given Dependant object.
    """

    flat_dependant = get_flat_dependant(dependant)
    if not flat_dependant.body_params:
        return None

    first_param = flat_dependant.body_params[0]
    field_info = first_param.field_info

    # Handle the case where there is only one body parameter and it is embedded
    embed = getattr(field_info, "embed", None)
    body_param_names_set = {param.name for param in flat_dependant.body_params}
    if len(body_param_names_set) == 1 and not embed:
        return first_param

    # If one field requires to embed, all have to be embedded
    for param in flat_dependant.body_params:
        setattr(param.field_info, "embed", True)  # noqa: B010

    # Generate a custom body model for this endpoint
    model_name = "Body_" + name
    body_model = create_body_model(fields=flat_dependant.body_params, model_name=model_name)

    required = any(True for f in flat_dependant.body_params if f.required)

    body_field_info, body_field_info_kwargs = get_body_field_info(
        body_model=body_model,
        flat_dependant=flat_dependant,
        required=required,
    )

    final_field = create_response_field(
        name="body",
        type_=body_model,
        required=required,
        alias="body",
        field_info=body_field_info(**body_field_info_kwargs),
    )
    return final_field

get_body_field_info

get_body_field_info(
    *,
    body_model: type[BaseModel],
    flat_dependant: Dependant,
    required: bool
) -> tuple[type[Body], dict[str, Any]]

Get the Body field info and kwargs for a given body model.

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def get_body_field_info(
    *,
    body_model: type[BaseModel],
    flat_dependant: Dependant,
    required: bool,
) -> tuple[type[Body], dict[str, Any]]:
    """
    Get the Body field info and kwargs for a given body model.
    """

    body_field_info_kwargs: dict[str, Any] = {"annotation": body_model, "alias": "body"}

    if not required:
        body_field_info_kwargs["default"] = None

    if any(isinstance(f.field_info, _File) for f in flat_dependant.body_params):
        # MAINTENANCE: body_field_info: type[Body] = _File
        raise NotImplementedError("_File fields are not supported in request bodies")
    elif any(isinstance(f.field_info, _Form) for f in flat_dependant.body_params):
        # MAINTENANCE: body_field_info: type[Body] = _Form
        raise NotImplementedError("_Form fields are not supported in request bodies")
    else:
        body_field_info = Body

        body_param_media_types = [
            f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, Body)
        ]
        if len(set(body_param_media_types)) == 1:
            body_field_info_kwargs["media_type"] = body_param_media_types[0]

    return body_field_info, body_field_info_kwargs

get_dependant

get_dependant(
    *,
    path: str,
    call: Callable[..., Any],
    name: str | None = None,
    responses: dict[int, OpenAPIResponse] | None = None
) -> Dependant

Returns a dependant model for a handler function. A dependant model is a model that contains the parameters and return value of a handler function.

PARAMETER DESCRIPTION
path

The path template

TYPE: str

call

The handler function

TYPE: Callable[..., Any]

name

The name of the handler function

TYPE: str | None DEFAULT: None

responses

The list of extra responses for the handler function

TYPE: dict[int, OpenAPIResponse] | None DEFAULT: None

RETURNS DESCRIPTION
Dependant

The dependant model for the handler function

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def get_dependant(
    *,
    path: str,
    call: Callable[..., Any],
    name: str | None = None,
    responses: dict[int, OpenAPIResponse] | None = None,
) -> Dependant:
    """
    Returns a dependant model for a handler function. A dependant model is a model that contains
    the parameters and return value of a handler function.

    Parameters
    ----------
    path: str
        The path template
    call: Callable[..., Any]
        The handler function
    name: str, optional
        The name of the handler function
    responses: list[dict[int, OpenAPIResponse]], optional
        The list of extra responses for the handler function

    Returns
    -------
    Dependant
        The dependant model for the handler function
    """
    path_param_names = get_path_param_names(path)
    endpoint_signature = get_typed_signature(call)
    signature_params = endpoint_signature.parameters

    dependant = Dependant(
        call=call,
        name=name,
        path=path,
    )

    # Add each parameter to the dependant model
    for param_name, param in signature_params.items():
        # If the parameter is a path parameter, we need to set the in_ field to "path".
        is_path_param = param_name in path_param_names

        # Analyze the parameter to get the Pydantic field.
        param_field = analyze_param(
            param_name=param_name,
            annotation=param.annotation,
            value=param.default,
            is_path_param=is_path_param,
            is_response_param=False,
        )
        if param_field is None:
            raise AssertionError(f"Parameter field is None for param: {param_name}")

        if is_body_param(param_field=param_field, is_path_param=is_path_param):
            dependant.body_params.append(param_field)
        else:
            add_param_to_fields(field=param_field, dependant=dependant)

    _add_return_annotation(dependant, endpoint_signature)
    _add_extra_responses(dependant, responses)

    return dependant

get_flat_params

get_flat_params(dependant: Dependant) -> list[ModelField]

Get a list of all the parameters from a Dependant object.

PARAMETER DESCRIPTION
dependant

The Dependant object containing the parameters.

TYPE: Dependant

RETURNS DESCRIPTION
list[ModelField]

A list of ModelField objects containing the flat parameters from the Dependant object.

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def get_flat_params(dependant: Dependant) -> list[ModelField]:
    """
    Get a list of all the parameters from a Dependant object.

    Parameters
    ----------
    dependant : Dependant
        The Dependant object containing the parameters.

    Returns
    -------
    list[ModelField]
        A list of ModelField objects containing the flat parameters from the Dependant object.

    """
    flat_dependant = get_flat_dependant(dependant)
    return (
        flat_dependant.path_params
        + flat_dependant.query_params
        + flat_dependant.header_params
        + flat_dependant.cookie_params
    )

get_path_param_names

get_path_param_names(path: str) -> set[str]

Returns the path parameter names from a path template. Those are the strings between { and }.

PARAMETER DESCRIPTION
path

The path template

TYPE: str

RETURNS DESCRIPTION
set[str]

The path parameter names

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def get_path_param_names(path: str) -> set[str]:
    """
    Returns the path parameter names from a path template. Those are the strings between { and }.

    Parameters
    ----------
    path: str
        The path template

    Returns
    -------
    set[str]
        The path parameter names

    """
    return set(re.findall("{(.*?)}", path))

get_typed_annotation

get_typed_annotation(
    annotation: Any, globalns: dict[str, Any]
) -> Any

Evaluates a type annotation, which can be a string or a ForwardRef.

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
82
83
84
85
86
87
88
89
def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any:
    """
    Evaluates a type annotation, which can be a string or a ForwardRef.
    """
    if isinstance(annotation, str):
        annotation = ForwardRef(annotation)
        annotation = evaluate_forwardref(annotation, globalns, globalns)
    return annotation

get_typed_signature

get_typed_signature(
    call: Callable[..., Any],
) -> inspect.Signature

Returns a typed signature for a callable, resolving forward references.

PARAMETER DESCRIPTION
call

The callable to get the signature for

TYPE: Callable[..., Any]

RETURNS DESCRIPTION
Signature

The typed signature

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
    """
    Returns a typed signature for a callable, resolving forward references.

    Parameters
    ----------
    call: Callable[..., Any]
        The callable to get the signature for

    Returns
    -------
    inspect.Signature
        The typed signature
    """
    signature = inspect.signature(call)

    # Gets the global namespace for the call. This is used to resolve forward references.
    globalns = getattr(call, "__globals__", {})

    typed_params = [
        inspect.Parameter(
            name=param.name,
            kind=param.kind,
            default=param.default,
            annotation=get_typed_annotation(param.annotation, globalns),
        )
        for param in signature.parameters.values()
    ]

    # If the return annotation is not empty, add it to the signature.
    if signature.return_annotation is not inspect.Signature.empty:
        return_param = inspect.Parameter(
            name="Return",
            kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
            default=None,
            annotation=get_typed_annotation(signature.return_annotation, globalns),
        )
        return inspect.Signature(typed_params, return_annotation=return_param.annotation)
    else:
        return inspect.Signature(typed_params)

is_body_param

is_body_param(
    *, param_field: ModelField, is_path_param: bool
) -> bool

Returns whether a parameter is a request body parameter, by checking if it is a scalar field or a body field.

PARAMETER DESCRIPTION
param_field

The parameter field

TYPE: ModelField

is_path_param

Whether the parameter is a path parameter

TYPE: bool

RETURNS DESCRIPTION
bool

Whether the parameter is a request body parameter

Source code in aws_lambda_powertools/event_handler/openapi/dependant.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool:
    """
    Returns whether a parameter is a request body parameter, by checking if it is a scalar field or a body field.

    Parameters
    ----------
    param_field: ModelField
        The parameter field
    is_path_param: bool
        Whether the parameter is a path parameter

    Returns
    -------
    bool
        Whether the parameter is a request body parameter
    """
    if is_path_param:
        if not is_scalar_field(field=param_field):
            raise AssertionError("Path params must be of one of the supported types")
        return False
    elif is_scalar_field(field=param_field):
        return False
    elif isinstance(param_field.field_info, (Query, Header)) and is_scalar_sequence_field(param_field):
        return False
    else:
        if not isinstance(param_field.field_info, Body):
            raise AssertionError(f"Param: {param_field.name} can only be a request body, use Body()")
        return True

encoders

FUNCTION DESCRIPTION
decimal_encoder

Encodes a Decimal as int of there's no exponent, otherwise float

iso_format

ISO format for date and time

jsonable_encoder

JSON encodes an arbitrary Python object into JSON serializable data types.

decimal_encoder

decimal_encoder(dec_value: Decimal) -> int | float

Encodes a Decimal as int of there's no exponent, otherwise float

This is useful when we use ConstrainedDecimal to represent Numeric(x,0) where an integer (but not int typed) is used. Encoding this as a float results in failed round-tripping between encode and parse.

decimal_encoder(Decimal("1.0")) 1.0

decimal_encoder(Decimal("1")) 1

Source code in aws_lambda_powertools/event_handler/openapi/encoders.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def decimal_encoder(dec_value: Decimal) -> int | float:
    """
    Encodes a Decimal as int of there's no exponent, otherwise float

    This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
    where an integer (but not int typed) is used. Encoding this as a float
    results in failed round-tripping between encode and parse.

    >>> decimal_encoder(Decimal("1.0"))
    1.0

    >>> decimal_encoder(Decimal("1"))
    1
    """
    if dec_value.as_tuple().exponent >= 0:  # type: ignore[operator]
        return int(dec_value)
    else:
        return float(dec_value)

iso_format

iso_format(o: datetime.date | datetime.time) -> str

ISO format for date and time

Source code in aws_lambda_powertools/event_handler/openapi/encoders.py
318
319
320
321
322
def iso_format(o: datetime.date | datetime.time) -> str:
    """
    ISO format for date and time
    """
    return o.isoformat()

jsonable_encoder

jsonable_encoder(
    obj: Any,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    by_alias: bool = True,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    custom_serializer: Callable[[Any], str] | None = None,
) -> Any

JSON encodes an arbitrary Python object into JSON serializable data types.

This is a modified version of fastapi.encoders.jsonable_encoder that supports encoding of pydantic.BaseModel objects.

PARAMETER DESCRIPTION
obj

The object to encode

TYPE: Any

include

A set or dictionary of strings that specifies which properties should be included, by default None, meaning everything is included

TYPE: IncEx | None DEFAULT: None

exclude

A set or dictionary of strings that specifies which properties should be excluded, by default None, meaning nothing is excluded

TYPE: IncEx | None DEFAULT: None

by_alias

Whether field aliases should be respected, by default True

TYPE: bool DEFAULT: True

exclude_unset

Whether fields that are not set should be excluded, by default False

TYPE: bool DEFAULT: False

exclude_defaults

Whether fields that are equal to their default value (as specified in the model) should be excluded, by default False

TYPE: bool DEFAULT: False

exclude_none

Whether fields that are equal to None should be excluded, by default False

TYPE: bool DEFAULT: False

custom_serializer

A custom serializer to use for encoding the object, when everything else fails.

TYPE: Callable DEFAULT: None

RETURNS DESCRIPTION
Any

The JSON serializable data types

Source code in aws_lambda_powertools/event_handler/openapi/encoders.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def jsonable_encoder(  # noqa: PLR0911
    obj: Any,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    by_alias: bool = True,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    custom_serializer: Callable[[Any], str] | None = None,
) -> Any:
    """
    JSON encodes an arbitrary Python object into JSON serializable data types.

    This is a modified version of fastapi.encoders.jsonable_encoder that supports
    encoding of pydantic.BaseModel objects.

    Parameters
    ----------
    obj : Any
        The object to encode
    include : IncEx | None, optional
        A set or dictionary of strings that specifies which properties should be included, by default None,
        meaning everything is included
    exclude : IncEx | None, optional
        A set or dictionary of strings that specifies which properties should be excluded, by default None,
        meaning nothing is excluded
    by_alias : bool, optional
        Whether field aliases should be respected, by default True
    exclude_unset : bool, optional
        Whether fields that are not set should be excluded, by default False
    exclude_defaults : bool, optional
        Whether fields that are equal to their default value (as specified in the model) should be excluded,
        by default False
    exclude_none : bool, optional
        Whether fields that are equal to None should be excluded, by default False
    custom_serializer : Callable, optional
        A custom serializer to use for encoding the object, when everything else fails.

    Returns
    -------
    Any
        The JSON serializable data types
    """
    if include is not None and not isinstance(include, (set, dict)):
        include = set(include)
    if exclude is not None and not isinstance(exclude, (set, dict)):
        exclude = set(exclude)

    try:
        # Pydantic models
        if isinstance(obj, BaseModel):
            return _dump_base_model(
                obj=obj,
                include=include,
                exclude=exclude,
                by_alias=by_alias,
                exclude_unset=exclude_unset,
                exclude_none=exclude_none,
                exclude_defaults=exclude_defaults,
            )

        # Dataclasses
        if dataclasses.is_dataclass(obj):
            obj_dict = dataclasses.asdict(obj)  # type: ignore[arg-type]
            return jsonable_encoder(
                obj_dict,
                include=include,
                exclude=exclude,
                by_alias=by_alias,
                exclude_unset=exclude_unset,
                exclude_defaults=exclude_defaults,
                exclude_none=exclude_none,
                custom_serializer=custom_serializer,
            )

        # Enums
        if isinstance(obj, Enum):
            return obj.value

        # Paths
        if isinstance(obj, PurePath):
            return str(obj)

        # Scalars
        if isinstance(obj, (str, int, float, type(None))):
            return obj

        # Dictionaries
        if isinstance(obj, dict):
            return _dump_dict(
                obj=obj,
                include=include,
                exclude=exclude,
                by_alias=by_alias,
                exclude_unset=exclude_unset,
                exclude_none=exclude_none,
                custom_serializer=custom_serializer,
            )

        # Sequences
        if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):
            return _dump_sequence(
                obj=obj,
                include=include,
                exclude=exclude,
                by_alias=by_alias,
                exclude_none=exclude_none,
                exclude_defaults=exclude_defaults,
                exclude_unset=exclude_unset,
                custom_serializer=custom_serializer,
            )

        # Other types
        if type(obj) in ENCODERS_BY_TYPE:
            return ENCODERS_BY_TYPE[type(obj)](obj)

        for encoder, classes_tuple in encoders_by_class_tuples.items():
            if isinstance(obj, classes_tuple):
                return encoder(obj)

        # Use custom serializer if present
        if custom_serializer:
            return custom_serializer(obj)

        # Default
        return _dump_other(
            obj=obj,
            include=include,
            exclude=exclude,
            by_alias=by_alias,
            exclude_none=exclude_none,
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            custom_serializer=custom_serializer,
        )
    except ValueError as exc:
        raise SerializationError(
            f"Unable to serialize the object {obj} as it is not a supported type. Error details: {exc}",
            "See: https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/#serializing-objects",
        ) from exc

exceptions

CLASS DESCRIPTION
RequestValidationError

Raised when the request body does not match the OpenAPI schema

SchemaValidationError

Raised when the OpenAPI schema validation fails

SerializationError

Base exception for all encoding errors

ValidationException

Base exception for all validation errors

RequestValidationError

RequestValidationError(
    errors: Sequence[Any], *, body: Any = None
)

Bases: ValidationException

Raised when the request body does not match the OpenAPI schema

Source code in aws_lambda_powertools/event_handler/openapi/exceptions.py
21
22
23
def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
    super().__init__(errors)
    self.body = body

SchemaValidationError

SchemaValidationError(errors: Sequence[Any])

Bases: ValidationException

Raised when the OpenAPI schema validation fails

Source code in aws_lambda_powertools/event_handler/openapi/exceptions.py
 9
10
def __init__(self, errors: Sequence[Any]) -> None:
    self._errors = errors

SerializationError

Bases: Exception

Base exception for all encoding errors

ValidationException

ValidationException(errors: Sequence[Any])

Bases: Exception

Base exception for all validation errors

Source code in aws_lambda_powertools/event_handler/openapi/exceptions.py
 9
10
def __init__(self, errors: Sequence[Any]) -> None:
    self._errors = errors

models

CLASS DESCRIPTION
OpenAPIExtensions

This class serves as a Pydantic proxy model to add OpenAPI extensions.

ATTRIBUTE DESCRIPTION
MODEL_CONFIG_IGNORE

The code defines Pydantic models for the various OpenAPI objects like OpenAPI, PathItem, Operation, Parameter etc.

MODEL_CONFIG_IGNORE module-attribute

MODEL_CONFIG_IGNORE = ConfigDict(extra='ignore')

The code defines Pydantic models for the various OpenAPI objects like OpenAPI, PathItem, Operation, Parameter etc. These models can be used to parse OpenAPI JSON/YAML files into Python objects, or generate OpenAPI from Python data.

OpenAPIExtensions

Bases: BaseModel

This class serves as a Pydantic proxy model to add OpenAPI extensions.

OpenAPI extensions are arbitrary fields, so we remove openapi_extensions when dumping and add only the provided value in the schema.

params

CLASS DESCRIPTION
Body

A class used internally to represent a body parameter in a path operation.

Dependant

A class used internally to represent a dependency between path operation decorators and the path operation function.

Header

A class used internally to represent a header parameter in a path operation.

Param

A class used internally to represent a parameter in a path operation.

Path

A class used internally to represent a path parameter in a path operation.

Query

A class used internally to represent a query parameter in a path operation.

FUNCTION DESCRIPTION
analyze_param

Analyze a parameter annotation and value to determine the type and default value of the parameter.

create_response_field

Create a new response field. Raises if type_ is invalid.

get_field_info_and_type_annotation

Get the FieldInfo and type annotation from an annotation and value.

get_field_info_annotated_type

Get the FieldInfo and type annotation from an Annotated type.

get_flat_dependant

Flatten a recursive Dependant model structure.

Body

Body(
    default: Any = Undefined,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    embed: bool = False,
    media_type: str = "application/json",
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any
)

Bases: FieldInfo

A class used internally to represent a body parameter in a path operation.

Source code in aws_lambda_powertools/event_handler/openapi/params.py
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def __init__(
    self,
    default: Any = Undefined,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    embed: bool = False,
    media_type: str = "application/json",
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    # MAINTENANCE: update when deprecating Pydantic v1, import these types
    # str | AliasPath | AliasChoices | None
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any,
):
    self.embed = embed
    self.media_type = media_type
    self.deprecated = deprecated
    self.include_in_schema = include_in_schema
    kwargs = dict(
        default=default,
        default_factory=default_factory,
        alias=alias,
        title=title,
        description=description,
        gt=gt,
        ge=ge,
        lt=lt,
        le=le,
        min_length=min_length,
        max_length=max_length,
        discriminator=discriminator,
        multiple_of=multiple_of,
        allow_nan=allow_inf_nan,
        max_digits=max_digits,
        decimal_places=decimal_places,
        **extra,
    )
    if examples is not None:
        kwargs["examples"] = examples
    current_json_schema_extra = json_schema_extra or extra

    kwargs.update(
        {
            "annotation": annotation,
            "alias_priority": alias_priority,
            "validation_alias": validation_alias,
            "serialization_alias": serialization_alias,
            "strict": strict,
            "json_schema_extra": current_json_schema_extra,
            "pattern": pattern,
        },
    )

    use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}

    super().__init__(**use_kwargs)

Dependant

Dependant(
    *,
    path_params: list[ModelField] | None = None,
    query_params: list[ModelField] | None = None,
    header_params: list[ModelField] | None = None,
    cookie_params: list[ModelField] | None = None,
    body_params: list[ModelField] | None = None,
    return_param: ModelField | None = None,
    response_extra_models: list[ModelField] | None = None,
    name: str | None = None,
    call: Callable[..., Any] | None = None,
    request_param_name: str | None = None,
    websocket_param_name: str | None = None,
    http_connection_param_name: str | None = None,
    response_param_name: str | None = None,
    background_tasks_param_name: str | None = None,
    path: str | None = None
)

A class used internally to represent a dependency between path operation decorators and the path operation function.

Source code in aws_lambda_powertools/event_handler/openapi/params.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(
    self,
    *,
    path_params: list[ModelField] | None = None,
    query_params: list[ModelField] | None = None,
    header_params: list[ModelField] | None = None,
    cookie_params: list[ModelField] | None = None,
    body_params: list[ModelField] | None = None,
    return_param: ModelField | None = None,
    response_extra_models: list[ModelField] | None = None,
    name: str | None = None,
    call: Callable[..., Any] | None = None,
    request_param_name: str | None = None,
    websocket_param_name: str | None = None,
    http_connection_param_name: str | None = None,
    response_param_name: str | None = None,
    background_tasks_param_name: str | None = None,
    path: str | None = None,
) -> None:
    self.path_params = path_params or []
    self.query_params = query_params or []
    self.header_params = header_params or []
    self.cookie_params = cookie_params or []
    self.body_params = body_params or []
    self.return_param = return_param or None
    self.response_extra_models = response_extra_models or []
    self.request_param_name = request_param_name
    self.websocket_param_name = websocket_param_name
    self.http_connection_param_name = http_connection_param_name
    self.response_param_name = response_param_name
    self.background_tasks_param_name = background_tasks_param_name
    self.name = name
    self.call = call
    # Store the path to be able to re-generate a dependable from it in overrides
    self.path = path
    # Save the cache key at creation to optimize performance
    self.cache_key: CacheKey = self.call

Header

Header(
    default: Any = Undefined,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    convert_underscores: bool = True,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any
)

Bases: Param

A class used internally to represent a header parameter in a path operation.

PARAMETER DESCRIPTION
default

The default value of the parameter

TYPE: Any DEFAULT: Undefined

default_factory

Callable that will be called when a default value is needed for this field

TYPE: Callable[[], Any] | None DEFAULT: _Unset

annotation

The type annotation of the parameter

TYPE: Any | None DEFAULT: None

alias

The public name of the field

TYPE: str | None DEFAULT: None

alias_priority

Priority of the alias. This affects whether an alias generator is used

TYPE: int | None DEFAULT: _Unset

validation_alias

Alias to be used for validation only

TYPE: str | None DEFAULT: None

serialization_alias

Alias to be used for serialization only

TYPE: str | None DEFAULT: None

convert_underscores

If true convert "_" to "-" See RFC: https://www.rfc-editor.org/rfc/rfc9110.html#name-field-name-registry

TYPE: bool DEFAULT: True

title

The title of the parameter

TYPE: str | None DEFAULT: None

description

The description of the parameter

TYPE: str | None DEFAULT: None

gt

Only applies to numbers, required the field to be "greater than"

TYPE: float | None DEFAULT: None

ge

Only applies to numbers, required the field to be "greater than or equal"

TYPE: float | None DEFAULT: None

lt

Only applies to numbers, required the field to be "less than"

TYPE: float | None DEFAULT: None

le

Only applies to numbers, required the field to be "less than or equal"

TYPE: float | None DEFAULT: None

min_length

Only applies to strings, required the field to have a minimum length

TYPE: int | None DEFAULT: None

max_length

Only applies to strings, required the field to have a maximum length

TYPE: int | None DEFAULT: None

pattern

Only applies to strings, requires the field match against a regular expression pattern string

TYPE: str | None DEFAULT: None

discriminator

Parameter field name for discriminating the type in a tagged union

TYPE: str | None DEFAULT: None

strict

Enables Pydantic's strict mode for the field

TYPE: bool | None DEFAULT: _Unset

multiple_of

Only applies to numbers, requires the field to be a multiple of the given value

TYPE: float | None DEFAULT: _Unset

allow_inf_nan

Only applies to numbers, requires the field to allow infinity and NaN values

TYPE: bool | None DEFAULT: _Unset

max_digits

Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.

TYPE: int | None DEFAULT: _Unset

decimal_places

Only applies to Decimals, requires the field to have at most a number of decimal places

TYPE: int | None DEFAULT: _Unset

examples

A list of examples for the parameter

TYPE: list[Any] | None DEFAULT: None

deprecated

If True, the parameter will be marked as deprecated

TYPE: bool | None DEFAULT: None

include_in_schema

If False, the parameter will be excluded from the generated OpenAPI schema

TYPE: bool DEFAULT: True

json_schema_extra

Extra values to include in the generated OpenAPI schema

TYPE: dict[str, Any] | None DEFAULT: None

Source code in aws_lambda_powertools/event_handler/openapi/params.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def __init__(
    self,
    default: Any = Undefined,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    # MAINTENANCE: update when deprecating Pydantic v1, import these types
    # str | AliasPath | AliasChoices | None
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    convert_underscores: bool = True,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any,
):
    """
    Constructs a new Query param.

    Parameters
    ----------
    default: Any
        The default value of the parameter
    default_factory: Callable[[], Any], optional
        Callable that will be called when a default value is needed for this field
    annotation: Any, optional
        The type annotation of the parameter
    alias: str, optional
        The public name of the field
    alias_priority: int, optional
        Priority of the alias. This affects whether an alias generator is used
    validation_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for validation only
    serialization_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for serialization only
    convert_underscores: bool
        If true convert "_" to "-"
        See RFC: https://www.rfc-editor.org/rfc/rfc9110.html#name-field-name-registry
    title: str, optional
        The title of the parameter
    description: str, optional
        The description of the parameter
    gt: float, optional
        Only applies to numbers, required the field to be "greater than"
    ge: float, optional
        Only applies to numbers, required the field to be "greater than or equal"
    lt: float, optional
        Only applies to numbers, required the field to be "less than"
    le: float, optional
        Only applies to numbers, required the field to be "less than or equal"
    min_length: int, optional
        Only applies to strings, required the field to have a minimum length
    max_length: int, optional
        Only applies to strings, required the field to have a maximum length
    pattern: str, optional
        Only applies to strings, requires the field match against a regular expression pattern string
    discriminator: str, optional
        Parameter field name for discriminating the type in a tagged union
    strict: bool, optional
        Enables Pydantic's strict mode for the field
    multiple_of: float, optional
        Only applies to numbers, requires the field to be a multiple of the given value
    allow_inf_nan: bool, optional
        Only applies to numbers, requires the field to allow infinity and NaN values
    max_digits: int, optional
        Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.
    decimal_places: int, optional
        Only applies to Decimals, requires the field to have at most a number of decimal places
    examples: list[Any], optional
        A list of examples for the parameter
    deprecated: bool, optional
        If `True`, the parameter will be marked as deprecated
    include_in_schema: bool, optional
        If `False`, the parameter will be excluded from the generated OpenAPI schema
    json_schema_extra: dict[str, Any], optional
        Extra values to include in the generated OpenAPI schema
    """
    self.convert_underscores = convert_underscores
    self._alias = alias

    super().__init__(
        default=default,
        default_factory=default_factory,
        annotation=annotation,
        alias=self._alias,
        alias_priority=alias_priority,
        validation_alias=validation_alias,
        serialization_alias=serialization_alias,
        title=title,
        description=description,
        gt=gt,
        ge=ge,
        lt=lt,
        le=le,
        min_length=min_length,
        max_length=max_length,
        pattern=pattern,
        discriminator=discriminator,
        strict=strict,
        multiple_of=multiple_of,
        allow_inf_nan=allow_inf_nan,
        max_digits=max_digits,
        decimal_places=decimal_places,
        deprecated=deprecated,
        examples=examples,
        include_in_schema=include_in_schema,
        json_schema_extra=json_schema_extra,
        **extra,
    )

Param

Param(
    default: Any = Undefined,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any
)

Bases: FieldInfo

A class used internally to represent a parameter in a path operation.

PARAMETER DESCRIPTION
default

The default value of the parameter

TYPE: Any DEFAULT: Undefined

default_factory

Callable that will be called when a default value is needed for this field

TYPE: Callable[[], Any] | None DEFAULT: _Unset

annotation

The type annotation of the parameter

TYPE: Any | None DEFAULT: None

alias

The public name of the field

TYPE: str | None DEFAULT: None

alias_priority

Priority of the alias. This affects whether an alias generator is used

TYPE: int | None DEFAULT: _Unset

validation_alias

Alias to be used for validation only

TYPE: str | None DEFAULT: None

serialization_alias

Alias to be used for serialization only

TYPE: str | None DEFAULT: None

title

The title of the parameter

TYPE: str | None DEFAULT: None

description

The description of the parameter

TYPE: str | None DEFAULT: None

gt

Only applies to numbers, required the field to be "greater than"

TYPE: float | None DEFAULT: None

ge

Only applies to numbers, required the field to be "greater than or equal"

TYPE: float | None DEFAULT: None

lt

Only applies to numbers, required the field to be "less than"

TYPE: float | None DEFAULT: None

le

Only applies to numbers, required the field to be "less than or equal"

TYPE: float | None DEFAULT: None

min_length

Only applies to strings, required the field to have a minimum length

TYPE: int | None DEFAULT: None

max_length

Only applies to strings, required the field to have a maximum length

TYPE: int | None DEFAULT: None

pattern

Only applies to strings, requires the field match against a regular expression pattern string

TYPE: str | None DEFAULT: None

discriminator

Parameter field name for discriminating the type in a tagged union

TYPE: str | None DEFAULT: None

strict

Enables Pydantic's strict mode for the field

TYPE: bool | None DEFAULT: _Unset

multiple_of

Only applies to numbers, requires the field to be a multiple of the given value

TYPE: float | None DEFAULT: _Unset

allow_inf_nan

Only applies to numbers, requires the field to allow infinity and NaN values

TYPE: bool | None DEFAULT: _Unset

max_digits

Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.

TYPE: int | None DEFAULT: _Unset

decimal_places

Only applies to Decimals, requires the field to have at most a number of decimal places

TYPE: int | None DEFAULT: _Unset

examples

A list of examples for the parameter

TYPE: list[Any] | None DEFAULT: None

deprecated

If True, the parameter will be marked as deprecated

TYPE: bool | None DEFAULT: None

include_in_schema

If False, the parameter will be excluded from the generated OpenAPI schema

TYPE: bool DEFAULT: True

json_schema_extra

Extra values to include in the generated OpenAPI schema

TYPE: dict[str, Any] | None DEFAULT: None

Source code in aws_lambda_powertools/event_handler/openapi/params.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def __init__(
    self,
    default: Any = Undefined,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    # MAINTENANCE: update when deprecating Pydantic v1, import these types
    # MAINTENANCE: validation_alias: str | AliasPath | AliasChoices | None
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any,
):
    """
    Constructs a new Param.

    Parameters
    ----------
    default: Any
        The default value of the parameter
    default_factory: Callable[[], Any], optional
        Callable that will be called when a default value is needed for this field
    annotation: Any, optional
        The type annotation of the parameter
    alias: str, optional
        The public name of the field
    alias_priority: int, optional
        Priority of the alias. This affects whether an alias generator is used
    validation_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for validation only
    serialization_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for serialization only
    title: str, optional
        The title of the parameter
    description: str, optional
        The description of the parameter
    gt: float, optional
        Only applies to numbers, required the field to be "greater than"
    ge: float, optional
        Only applies to numbers, required the field to be "greater than or equal"
    lt: float, optional
        Only applies to numbers, required the field to be "less than"
    le: float, optional
        Only applies to numbers, required the field to be "less than or equal"
    min_length: int, optional
        Only applies to strings, required the field to have a minimum length
    max_length: int, optional
        Only applies to strings, required the field to have a maximum length
    pattern: str, optional
        Only applies to strings, requires the field match against a regular expression pattern string
    discriminator: str, optional
        Parameter field name for discriminating the type in a tagged union
    strict: bool, optional
        Enables Pydantic's strict mode for the field
    multiple_of: float, optional
        Only applies to numbers, requires the field to be a multiple of the given value
    allow_inf_nan: bool, optional
        Only applies to numbers, requires the field to allow infinity and NaN values
    max_digits: int, optional
        Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.
    decimal_places: int, optional
        Only applies to Decimals, requires the field to have at most a number of decimal places
    examples: list[Any], optional
        A list of examples for the parameter
    deprecated: bool, optional
        If `True`, the parameter will be marked as deprecated
    include_in_schema: bool, optional
        If `False`, the parameter will be excluded from the generated OpenAPI schema
    json_schema_extra: dict[str, Any], optional
        Extra values to include in the generated OpenAPI schema
    """
    self.deprecated = deprecated
    self.include_in_schema = include_in_schema

    kwargs = dict(
        default=default,
        default_factory=default_factory,
        alias=alias,
        title=title,
        description=description,
        gt=gt,
        ge=ge,
        lt=lt,
        le=le,
        min_length=min_length,
        max_length=max_length,
        discriminator=discriminator,
        multiple_of=multiple_of,
        allow_nan=allow_inf_nan,
        max_digits=max_digits,
        decimal_places=decimal_places,
        **extra,
    )
    if examples is not None:
        kwargs["examples"] = examples

    current_json_schema_extra = json_schema_extra or extra

    kwargs.update(
        {
            "annotation": annotation,
            "alias_priority": alias_priority,
            "validation_alias": validation_alias,
            "serialization_alias": serialization_alias,
            "strict": strict,
            "json_schema_extra": current_json_schema_extra,
            "pattern": pattern,
        },
    )

    use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}

    super().__init__(**use_kwargs)

Path

Path(
    default: Any = ...,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any
)

Bases: Param

A class used internally to represent a path parameter in a path operation.

PARAMETER DESCRIPTION
default

The default value of the parameter

TYPE: Any DEFAULT: ...

default_factory

Callable that will be called when a default value is needed for this field

TYPE: Callable[[], Any] | None DEFAULT: _Unset

annotation

The type annotation of the parameter

TYPE: Any | None DEFAULT: None

alias

The public name of the field

TYPE: str | None DEFAULT: None

alias_priority

Priority of the alias. This affects whether an alias generator is used

TYPE: int | None DEFAULT: _Unset

validation_alias

Alias to be used for validation only

TYPE: str | None DEFAULT: None

serialization_alias

Alias to be used for serialization only

TYPE: str | None DEFAULT: None

title

The title of the parameter

TYPE: str | None DEFAULT: None

description

The description of the parameter

TYPE: str | None DEFAULT: None

gt

Only applies to numbers, required the field to be "greater than"

TYPE: float | None DEFAULT: None

ge

Only applies to numbers, required the field to be "greater than or equal"

TYPE: float | None DEFAULT: None

lt

Only applies to numbers, required the field to be "less than"

TYPE: float | None DEFAULT: None

le

Only applies to numbers, required the field to be "less than or equal"

TYPE: float | None DEFAULT: None

min_length

Only applies to strings, required the field to have a minimum length

TYPE: int | None DEFAULT: None

max_length

Only applies to strings, required the field to have a maximum length

TYPE: int | None DEFAULT: None

pattern

Only applies to strings, requires the field match against a regular expression pattern string

TYPE: str | None DEFAULT: None

discriminator

Parameter field name for discriminating the type in a tagged union

TYPE: str | None DEFAULT: None

strict

Enables Pydantic's strict mode for the field

TYPE: bool | None DEFAULT: _Unset

multiple_of

Only applies to numbers, requires the field to be a multiple of the given value

TYPE: float | None DEFAULT: _Unset

allow_inf_nan

Only applies to numbers, requires the field to allow infinity and NaN values

TYPE: bool | None DEFAULT: _Unset

max_digits

Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.

TYPE: int | None DEFAULT: _Unset

decimal_places

Only applies to Decimals, requires the field to have at most a number of decimal places

TYPE: int | None DEFAULT: _Unset

examples

A list of examples for the parameter

TYPE: list[Any] | None DEFAULT: None

deprecated

If True, the parameter will be marked as deprecated

TYPE: bool | None DEFAULT: None

include_in_schema

If False, the parameter will be excluded from the generated OpenAPI schema

TYPE: bool DEFAULT: True

json_schema_extra

Extra values to include in the generated OpenAPI schema

TYPE: dict[str, Any] | None DEFAULT: None

Source code in aws_lambda_powertools/event_handler/openapi/params.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def __init__(
    self,
    default: Any = ...,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    # MAINTENANCE: update when deprecating Pydantic v1, import these types
    # MAINTENANCE: validation_alias: str | AliasPath | AliasChoices | None
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any,
):
    """
    Constructs a new Path param.

    Parameters
    ----------
    default: Any
        The default value of the parameter
    default_factory: Callable[[], Any], optional
        Callable that will be called when a default value is needed for this field
    annotation: Any, optional
        The type annotation of the parameter
    alias: str, optional
        The public name of the field
    alias_priority: int, optional
        Priority of the alias. This affects whether an alias generator is used
    validation_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for validation only
    serialization_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for serialization only
    title: str, optional
        The title of the parameter
    description: str, optional
        The description of the parameter
    gt: float, optional
        Only applies to numbers, required the field to be "greater than"
    ge: float, optional
        Only applies to numbers, required the field to be "greater than or equal"
    lt: float, optional
        Only applies to numbers, required the field to be "less than"
    le: float, optional
        Only applies to numbers, required the field to be "less than or equal"
    min_length: int, optional
        Only applies to strings, required the field to have a minimum length
    max_length: int, optional
        Only applies to strings, required the field to have a maximum length
    pattern: str, optional
        Only applies to strings, requires the field match against a regular expression pattern string
    discriminator: str, optional
        Parameter field name for discriminating the type in a tagged union
    strict: bool, optional
        Enables Pydantic's strict mode for the field
    multiple_of: float, optional
        Only applies to numbers, requires the field to be a multiple of the given value
    allow_inf_nan: bool, optional
        Only applies to numbers, requires the field to allow infinity and NaN values
    max_digits: int, optional
        Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.
    decimal_places: int, optional
        Only applies to Decimals, requires the field to have at most a number of decimal places
    examples: list[Any], optional
        A list of examples for the parameter
    deprecated: bool, optional
        If `True`, the parameter will be marked as deprecated
    include_in_schema: bool, optional
        If `False`, the parameter will be excluded from the generated OpenAPI schema
    json_schema_extra: dict[str, Any], optional
        Extra values to include in the generated OpenAPI schema
    """
    if default is not ...:
        raise AssertionError("Path parameters cannot have a default value")

    super().__init__(
        default=default,
        default_factory=default_factory,
        annotation=annotation,
        alias=alias,
        alias_priority=alias_priority,
        validation_alias=validation_alias,
        serialization_alias=serialization_alias,
        title=title,
        description=description,
        gt=gt,
        ge=ge,
        lt=lt,
        le=le,
        min_length=min_length,
        max_length=max_length,
        pattern=pattern,
        discriminator=discriminator,
        strict=strict,
        multiple_of=multiple_of,
        allow_inf_nan=allow_inf_nan,
        max_digits=max_digits,
        decimal_places=decimal_places,
        deprecated=deprecated,
        examples=examples,
        include_in_schema=include_in_schema,
        json_schema_extra=json_schema_extra,
        **extra,
    )

Query

Query(
    default: Any = _Unset,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any
)

Bases: Param

A class used internally to represent a query parameter in a path operation.

PARAMETER DESCRIPTION
default

The default value of the parameter

TYPE: Any DEFAULT: _Unset

default_factory

Callable that will be called when a default value is needed for this field

TYPE: Callable[[], Any] | None DEFAULT: _Unset

annotation

The type annotation of the parameter

TYPE: Any | None DEFAULT: None

alias

The public name of the field

TYPE: str | None DEFAULT: None

alias_priority

Priority of the alias. This affects whether an alias generator is used

TYPE: int | None DEFAULT: _Unset

validation_alias

Alias to be used for validation only

TYPE: str | None DEFAULT: None

serialization_alias

Alias to be used for serialization only

TYPE: str | None DEFAULT: None

title

The title of the parameter

TYPE: str | None DEFAULT: None

description

The description of the parameter

TYPE: str | None DEFAULT: None

gt

Only applies to numbers, required the field to be "greater than"

TYPE: float | None DEFAULT: None

ge

Only applies to numbers, required the field to be "greater than or equal"

TYPE: float | None DEFAULT: None

lt

Only applies to numbers, required the field to be "less than"

TYPE: float | None DEFAULT: None

le

Only applies to numbers, required the field to be "less than or equal"

TYPE: float | None DEFAULT: None

min_length

Only applies to strings, required the field to have a minimum length

TYPE: int | None DEFAULT: None

max_length

Only applies to strings, required the field to have a maximum length

TYPE: int | None DEFAULT: None

pattern

Only applies to strings, requires the field match against a regular expression pattern string

TYPE: str | None DEFAULT: None

discriminator

Parameter field name for discriminating the type in a tagged union

TYPE: str | None DEFAULT: None

strict

Enables Pydantic's strict mode for the field

TYPE: bool | None DEFAULT: _Unset

multiple_of

Only applies to numbers, requires the field to be a multiple of the given value

TYPE: float | None DEFAULT: _Unset

allow_inf_nan

Only applies to numbers, requires the field to allow infinity and NaN values

TYPE: bool | None DEFAULT: _Unset

max_digits

Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.

TYPE: int | None DEFAULT: _Unset

decimal_places

Only applies to Decimals, requires the field to have at most a number of decimal places

TYPE: int | None DEFAULT: _Unset

examples

A list of examples for the parameter

TYPE: list[Any] | None DEFAULT: None

deprecated

If True, the parameter will be marked as deprecated

TYPE: bool | None DEFAULT: None

include_in_schema

If False, the parameter will be excluded from the generated OpenAPI schema

TYPE: bool DEFAULT: True

json_schema_extra

Extra values to include in the generated OpenAPI schema

TYPE: dict[str, Any] | None DEFAULT: None

Source code in aws_lambda_powertools/event_handler/openapi/params.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def __init__(
    self,
    default: Any = _Unset,
    *,
    default_factory: Callable[[], Any] | None = _Unset,
    annotation: Any | None = None,
    alias: str | None = None,
    alias_priority: int | None = _Unset,
    validation_alias: str | None = None,
    serialization_alias: str | None = None,
    title: str | None = None,
    description: str | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    discriminator: str | None = None,
    strict: bool | None = _Unset,
    multiple_of: float | None = _Unset,
    allow_inf_nan: bool | None = _Unset,
    max_digits: int | None = _Unset,
    decimal_places: int | None = _Unset,
    examples: list[Any] | None = None,
    deprecated: bool | None = None,
    include_in_schema: bool = True,
    json_schema_extra: dict[str, Any] | None = None,
    **extra: Any,
):
    """
    Constructs a new Query param.

    Parameters
    ----------
    default: Any
        The default value of the parameter
    default_factory: Callable[[], Any], optional
        Callable that will be called when a default value is needed for this field
    annotation: Any, optional
        The type annotation of the parameter
    alias: str, optional
        The public name of the field
    alias_priority: int, optional
        Priority of the alias. This affects whether an alias generator is used
    validation_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for validation only
    serialization_alias: str | AliasPath | AliasChoices | None, optional
        Alias to be used for serialization only
    title: str, optional
        The title of the parameter
    description: str, optional
        The description of the parameter
    gt: float, optional
        Only applies to numbers, required the field to be "greater than"
    ge: float, optional
        Only applies to numbers, required the field to be "greater than or equal"
    lt: float, optional
        Only applies to numbers, required the field to be "less than"
    le: float, optional
        Only applies to numbers, required the field to be "less than or equal"
    min_length: int, optional
        Only applies to strings, required the field to have a minimum length
    max_length: int, optional
        Only applies to strings, required the field to have a maximum length
    pattern: str, optional
        Only applies to strings, requires the field match against a regular expression pattern string
    discriminator: str, optional
        Parameter field name for discriminating the type in a tagged union
    strict: bool, optional
        Enables Pydantic's strict mode for the field
    multiple_of: float, optional
        Only applies to numbers, requires the field to be a multiple of the given value
    allow_inf_nan: bool, optional
        Only applies to numbers, requires the field to allow infinity and NaN values
    max_digits: int, optional
        Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.
    decimal_places: int, optional
        Only applies to Decimals, requires the field to have at most a number of decimal places
    examples: list[Any], optional
        A list of examples for the parameter
    deprecated: bool, optional
        If `True`, the parameter will be marked as deprecated
    include_in_schema: bool, optional
        If `False`, the parameter will be excluded from the generated OpenAPI schema
    json_schema_extra: dict[str, Any], optional
        Extra values to include in the generated OpenAPI schema
    """
    super().__init__(
        default=default,
        default_factory=default_factory,
        annotation=annotation,
        alias=alias,
        alias_priority=alias_priority,
        validation_alias=validation_alias,
        serialization_alias=serialization_alias,
        title=title,
        description=description,
        gt=gt,
        ge=ge,
        lt=lt,
        le=le,
        min_length=min_length,
        max_length=max_length,
        pattern=pattern,
        discriminator=discriminator,
        strict=strict,
        multiple_of=multiple_of,
        allow_inf_nan=allow_inf_nan,
        max_digits=max_digits,
        decimal_places=decimal_places,
        deprecated=deprecated,
        examples=examples,
        include_in_schema=include_in_schema,
        json_schema_extra=json_schema_extra,
        **extra,
    )

analyze_param

analyze_param(
    *,
    param_name: str,
    annotation: Any,
    value: Any,
    is_path_param: bool,
    is_response_param: bool
) -> ModelField | None

Analyze a parameter annotation and value to determine the type and default value of the parameter.

PARAMETER DESCRIPTION
param_name

The name of the parameter

TYPE: str

annotation

The annotation of the parameter

TYPE: Any

value

The value of the parameter

TYPE: Any

is_path_param

Whether the parameter is a path parameter

TYPE: bool

is_response_param

Whether the parameter is the return annotation

TYPE: bool

RETURNS DESCRIPTION
ModelField | None

The type annotation and the Pydantic field representing the parameter

Source code in aws_lambda_powertools/event_handler/openapi/params.py
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
def analyze_param(
    *,
    param_name: str,
    annotation: Any,
    value: Any,
    is_path_param: bool,
    is_response_param: bool,
) -> ModelField | None:
    """
    Analyze a parameter annotation and value to determine the type and default value of the parameter.

    Parameters
    ----------
    param_name: str
        The name of the parameter
    annotation
        The annotation of the parameter
    value
        The value of the parameter
    is_path_param
        Whether the parameter is a path parameter
    is_response_param
        Whether the parameter is the return annotation

    Returns
    -------
    ModelField | None
        The type annotation and the Pydantic field representing the parameter
    """
    field_info, type_annotation = get_field_info_and_type_annotation(
        annotation, value, is_path_param, is_response_param,
    )

    # If the value is a FieldInfo, we use it as the FieldInfo for the parameter
    if isinstance(value, FieldInfo):
        if field_info is not None:
            raise AssertionError("Cannot use a FieldInfo as a parameter annotation and pass a FieldInfo as a value")
        field_info = value

        field_info.annotation = type_annotation  # type: ignore[attr-defined,unused-ignore]

    # If we didn't determine the FieldInfo yet, we create a default one
    if field_info is None:
        default_value = value if value is not inspect.Signature.empty else Required

        # Check if the parameter is part of the path. Otherwise, defaults to query.
        if is_path_param:
            field_info = Path(annotation=type_annotation)
        elif not field_annotation_is_scalar(annotation=type_annotation):
            field_info = Body(annotation=type_annotation, default=default_value)
        else:
            field_info = Query(annotation=type_annotation, default=default_value)

    # When we have a response field, we need to set the default value to Required
    if is_response_param:
        field_info.default = Required

    field = _create_model_field(field_info, type_annotation, param_name, is_path_param)
    return field

create_response_field

create_response_field(
    name: str,
    type_: type[Any],
    default: Any | None = Undefined,
    required: bool | UndefinedType = Undefined,
    model_config: type[BaseConfig] = BaseConfig,
    field_info: FieldInfo | None = None,
    alias: str | None = None,
    mode: Literal[
        "validation", "serialization"
    ] = "validation",
) -> ModelField

Create a new response field. Raises if type_ is invalid.

Source code in aws_lambda_powertools/event_handler/openapi/params.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
def create_response_field(
    name: str,
    type_: type[Any],
    default: Any | None = Undefined,
    required: bool | UndefinedType = Undefined,
    model_config: type[BaseConfig] = BaseConfig,
    field_info: FieldInfo | None = None,
    alias: str | None = None,
    mode: Literal["validation", "serialization"] = "validation",
) -> ModelField:
    """
    Create a new response field. Raises if type_ is invalid.
    """
    field_info = field_info or FieldInfo(
        annotation=type_,
        default=default,
        alias=alias,
    )

    kwargs = {"name": name, "field_info": field_info, "mode": mode}

    return ModelField(**kwargs)  # type: ignore[arg-type]

get_field_info_and_type_annotation

get_field_info_and_type_annotation(
    annotation,
    value,
    is_path_param: bool,
    is_response_param: bool,
) -> tuple[FieldInfo | None, Any]

Get the FieldInfo and type annotation from an annotation and value.

Source code in aws_lambda_powertools/event_handler/openapi/params.py
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
def get_field_info_and_type_annotation(
    annotation, value, is_path_param: bool, is_response_param: bool,
) -> tuple[FieldInfo | None, Any]:
    """
    Get the FieldInfo and type annotation from an annotation and value.
    """
    field_info: FieldInfo | None = None
    type_annotation: Any = Any

    if annotation is not inspect.Signature.empty:
        # If the annotation is an Annotated type, we need to extract the type annotation and the FieldInfo
        if get_origin(annotation) is Annotated:
            field_info, type_annotation = get_field_info_annotated_type(annotation, value, is_path_param)
        # If the annotation is a Response type, we recursively call this function with the inner type
        elif get_origin(annotation) is Response:
            field_info, type_annotation = get_field_info_response_type(annotation, value)
        # If the response param is a tuple with two elements, we use the first element as the type annotation,
        # just like we did in the APIGateway._to_response
        elif is_response_param and get_origin(annotation) is tuple and len(get_args(annotation)) == 2:
            field_info, type_annotation = get_field_info_tuple_type(annotation, value)
        # If the annotation is not an Annotated type, we use it as the type annotation
        else:
            type_annotation = annotation

    return field_info, type_annotation

get_field_info_annotated_type

get_field_info_annotated_type(
    annotation, value, is_path_param: bool
) -> tuple[FieldInfo | None, Any]

Get the FieldInfo and type annotation from an Annotated type.

Source code in aws_lambda_powertools/event_handler/openapi/params.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
def get_field_info_annotated_type(annotation, value, is_path_param: bool) -> tuple[FieldInfo | None, Any]:
    """
    Get the FieldInfo and type annotation from an Annotated type.
    """
    field_info: FieldInfo | None = None
    annotated_args = get_args(annotation)
    type_annotation = annotated_args[0]
    powertools_annotations = [arg for arg in annotated_args[1:] if isinstance(arg, FieldInfo)]

    if len(powertools_annotations) > 1:
        raise AssertionError("Only one FieldInfo can be used per parameter")

    powertools_annotation = next(iter(powertools_annotations), None)

    if isinstance(powertools_annotation, FieldInfo):
        # Copy `field_info` because we mutate `field_info.default` later
        field_info = copy_field_info(
            field_info=powertools_annotation,
            annotation=annotation,
        )
        if field_info.default not in [Undefined, Required]:
            raise AssertionError("FieldInfo needs to have a default value of Undefined or Required")

        if value is not inspect.Signature.empty:
            if is_path_param:
                raise AssertionError("Cannot use a FieldInfo as a path parameter and pass a value")
            field_info.default = value
        else:
            field_info.default = Required

    return field_info, type_annotation

get_flat_dependant

get_flat_dependant(
    dependant: Dependant,
    visited: list[CacheKey] | None = None,
) -> Dependant

Flatten a recursive Dependant model structure.

This function recursively concatenates the parameter fields of a Dependant model and its dependencies into a flat Dependant structure. This is useful for scenarios like parameter validation where the nested structure is not relevant.

PARAMETER DESCRIPTION
dependant

The dependant model to flatten

TYPE: Dependant

visited

Keeps track of visited Dependents to avoid infinite recursion. Defaults to empty list.

TYPE: list[CacheKey] | None DEFAULT: None

RETURNS DESCRIPTION
Dependant

The flattened Dependant model

Source code in aws_lambda_powertools/event_handler/openapi/params.py
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
def get_flat_dependant(
    dependant: Dependant,
    visited: list[CacheKey] | None = None,
) -> Dependant:
    """
    Flatten a recursive Dependant model structure.

    This function recursively concatenates the parameter fields of a Dependant model and its dependencies into a flat
    Dependant structure. This is useful for scenarios like parameter validation where the nested structure is not
    relevant.

    Parameters
    ----------
    dependant: Dependant
        The dependant model to flatten
    visited: list[CacheKey], optional
        Keeps track of visited Dependents to avoid infinite recursion. Defaults to empty list.

    Returns
    -------
    Dependant
        The flattened Dependant model
    """
    if visited is None:
        visited = []
    visited.append(dependant.cache_key)

    return Dependant(
        path_params=dependant.path_params.copy(),
        query_params=dependant.query_params.copy(),
        header_params=dependant.header_params.copy(),
        cookie_params=dependant.cookie_params.copy(),
        body_params=dependant.body_params.copy(),
        path=dependant.path,
    )

swagger_ui

MODULE DESCRIPTION
html
oauth2
CLASS DESCRIPTION
OAuth2Config

OAuth2 configuration for Swagger UI

FUNCTION DESCRIPTION
generate_oauth2_redirect_html

Generates the HTML content for the OAuth2 redirect page.

generate_swagger_html

Generate Swagger UI HTML page

OAuth2Config

Bases: BaseModel

OAuth2 configuration for Swagger UI

generate_oauth2_redirect_html

generate_oauth2_redirect_html() -> str

Generates the HTML content for the OAuth2 redirect page.

Source: https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html

Source code in aws_lambda_powertools/event_handler/openapi/swagger_ui/oauth2.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def generate_oauth2_redirect_html() -> str:
    """
    Generates the HTML content for the OAuth2 redirect page.

    Source: https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html
    """
    return """
<!doctype html>
<html lang="en-US">
<head>
    <title>Swagger UI: OAuth2 Redirect</title>
</head>
<body>
<script>
    'use strict';
    function run () {
        var oauth2 = window.opener.swaggerUIRedirectOauth2;
        var sentState = oauth2.state;
        var redirectUrl = oauth2.redirectUrl;
        var isValid, qp, arr;

        if (/code|token|error/.test(window.location.hash)) {
            qp = window.location.hash.substring(1).replace('?', '&');
        } else {
            qp = location.search.substring(1);
        }

        arr = qp.split("&");
        arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';});
        qp = qp ? JSON.parse('{' + arr.join() + '}',
                function (key, value) {
                    return key === "" ? value : decodeURIComponent(value);
                }
        ) : {};

        isValid = qp.state === sentState;

        if ((
          oauth2.auth.schema.get("flow") === "accessCode" ||
          oauth2.auth.schema.get("flow") === "authorizationCode" ||
          oauth2.auth.schema.get("flow") === "authorization_code"
        ) && !oauth2.auth.code) {
            if (!isValid) {
                oauth2.errCb({
                    authId: oauth2.auth.name,
                    source: "auth",
                    level: "warning",
                    message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server."
                });
            }

            if (qp.code) {
                delete oauth2.state;
                oauth2.auth.code = qp.code;
                oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
            } else {
                let oauthErrorMsg;
                if (qp.error) {
                    oauthErrorMsg = "["+qp.error+"]: " +
                        (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
                        (qp.error_uri ? "More info: "+qp.error_uri : "");
                }

                oauth2.errCb({
                    authId: oauth2.auth.name,
                    source: "auth",
                    level: "error",
                    message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server."
                });
            }
        } else {
            oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
        }
        window.close();
    }

    if (document.readyState !== 'loading') {
        run();
    } else {
        document.addEventListener('DOMContentLoaded', function () {
            run();
        });
    }
</script>
</body>
</html>
    """.strip()

generate_swagger_html

generate_swagger_html(
    spec: str,
    swagger_js: str,
    swagger_css: str,
    swagger_base_url: str,
    oauth2_config: OAuth2Config | None,
    persist_authorization: bool = False,
) -> str

Generate Swagger UI HTML page

PARAMETER DESCRIPTION
spec

The OpenAPI spec

TYPE: str

swagger_js

Swagger UI JavaScript source code or URL

TYPE: str

swagger_css

Swagger UI CSS source code or URL

TYPE: str

swagger_base_url

The base URL for Swagger UI

TYPE: str

oauth2_config

The OAuth2 configuration.

TYPE: OAuth2Config | None

persist_authorization

Whether to persist authorization data on browser close/refresh.

TYPE: bool DEFAULT: False

Source code in aws_lambda_powertools/event_handler/openapi/swagger_ui/html.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def generate_swagger_html(
    spec: str,
    swagger_js: str,
    swagger_css: str,
    swagger_base_url: str,
    oauth2_config: OAuth2Config | None,
    persist_authorization: bool = False,
) -> str:
    """
    Generate Swagger UI HTML page

    Parameters
    ----------
    spec: str
        The OpenAPI spec
    swagger_js: str
        Swagger UI JavaScript source code or URL
    swagger_css: str
        Swagger UI CSS source code or URL
    swagger_base_url: str
        The base URL for Swagger UI
    oauth2_config: OAuth2Config, optional
        The OAuth2 configuration.
    persist_authorization: bool, optional
        Whether to persist authorization data on browser close/refresh.
    """

    # If Swagger base URL is present, generate HTML content with linked CSS and JavaScript files
    # If no Swagger base URL is provided, include CSS and JavaScript directly in the HTML
    if swagger_base_url:
        swagger_css_content = f"<link rel='stylesheet' type='text/css' href='{swagger_css}'>"
        swagger_js_content = f"<script src='{swagger_js}'></script>"
    else:
        swagger_css_content = f"<style>{swagger_css}</style>"
        swagger_js_content = f"<script>{swagger_js}</script>"

    # Prepare oauth2 config
    oauth2_content = (
        f"ui.initOAuth({oauth2_config.json(exclude_none=True, exclude_unset=True)});" if oauth2_config else ""
    )

    return f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <meta
      http-equiv="Cache-control"
      content="no-cache, no-store, must-revalidate"
    />
    {swagger_css_content}
</head>

<body>
    <div id="swagger-ui">
        Loading...
    </div>
</body>

{swagger_js_content}

<script>
  var currentUrl = new URL(window.location.href);
  var baseUrl = currentUrl.protocol + "//" + currentUrl.host + currentUrl.pathname;

  var swaggerUIOptions = {{
    dom_id: "#swagger-ui",
    docExpansion: "list",
    deepLinking: true,
    filter: true,
    layout: "BaseLayout",
    showExtensions: true,
    showCommonExtensions: true,
    spec: {spec},
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIBundle.SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    withCredentials: true,
    persistAuthorization: {str(persist_authorization).lower()},
    oauth2RedirectUrl: baseUrl + "?format=oauth2-redirect",
  }}

  var ui = SwaggerUIBundle(swaggerUIOptions)
  ui.specActions.updateUrl(currentUrl.pathname + "?format=json");
  {oauth2_content}
</script>
</html>
            """.strip()

html

FUNCTION DESCRIPTION
generate_swagger_html

Generate Swagger UI HTML page

generate_swagger_html

generate_swagger_html(
    spec: str,
    swagger_js: str,
    swagger_css: str,
    swagger_base_url: str,
    oauth2_config: OAuth2Config | None,
    persist_authorization: bool = False,
) -> str

Generate Swagger UI HTML page

PARAMETER DESCRIPTION
spec

The OpenAPI spec

TYPE: str

swagger_js

Swagger UI JavaScript source code or URL

TYPE: str

swagger_css

Swagger UI CSS source code or URL

TYPE: str

swagger_base_url

The base URL for Swagger UI

TYPE: str

oauth2_config

The OAuth2 configuration.

TYPE: OAuth2Config | None

persist_authorization

Whether to persist authorization data on browser close/refresh.

TYPE: bool DEFAULT: False

Source code in aws_lambda_powertools/event_handler/openapi/swagger_ui/html.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def generate_swagger_html(
    spec: str,
    swagger_js: str,
    swagger_css: str,
    swagger_base_url: str,
    oauth2_config: OAuth2Config | None,
    persist_authorization: bool = False,
) -> str:
    """
    Generate Swagger UI HTML page

    Parameters
    ----------
    spec: str
        The OpenAPI spec
    swagger_js: str
        Swagger UI JavaScript source code or URL
    swagger_css: str
        Swagger UI CSS source code or URL
    swagger_base_url: str
        The base URL for Swagger UI
    oauth2_config: OAuth2Config, optional
        The OAuth2 configuration.
    persist_authorization: bool, optional
        Whether to persist authorization data on browser close/refresh.
    """

    # If Swagger base URL is present, generate HTML content with linked CSS and JavaScript files
    # If no Swagger base URL is provided, include CSS and JavaScript directly in the HTML
    if swagger_base_url:
        swagger_css_content = f"<link rel='stylesheet' type='text/css' href='{swagger_css}'>"
        swagger_js_content = f"<script src='{swagger_js}'></script>"
    else:
        swagger_css_content = f"<style>{swagger_css}</style>"
        swagger_js_content = f"<script>{swagger_js}</script>"

    # Prepare oauth2 config
    oauth2_content = (
        f"ui.initOAuth({oauth2_config.json(exclude_none=True, exclude_unset=True)});" if oauth2_config else ""
    )

    return f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <meta
      http-equiv="Cache-control"
      content="no-cache, no-store, must-revalidate"
    />
    {swagger_css_content}
</head>

<body>
    <div id="swagger-ui">
        Loading...
    </div>
</body>

{swagger_js_content}

<script>
  var currentUrl = new URL(window.location.href);
  var baseUrl = currentUrl.protocol + "//" + currentUrl.host + currentUrl.pathname;

  var swaggerUIOptions = {{
    dom_id: "#swagger-ui",
    docExpansion: "list",
    deepLinking: true,
    filter: true,
    layout: "BaseLayout",
    showExtensions: true,
    showCommonExtensions: true,
    spec: {spec},
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIBundle.SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    withCredentials: true,
    persistAuthorization: {str(persist_authorization).lower()},
    oauth2RedirectUrl: baseUrl + "?format=oauth2-redirect",
  }}

  var ui = SwaggerUIBundle(swaggerUIOptions)
  ui.specActions.updateUrl(currentUrl.pathname + "?format=json");
  {oauth2_content}
</script>
</html>
            """.strip()

oauth2

CLASS DESCRIPTION
OAuth2Config

OAuth2 configuration for Swagger UI

FUNCTION DESCRIPTION
generate_oauth2_redirect_html

Generates the HTML content for the OAuth2 redirect page.

OAuth2Config

Bases: BaseModel

OAuth2 configuration for Swagger UI

generate_oauth2_redirect_html

generate_oauth2_redirect_html() -> str

Generates the HTML content for the OAuth2 redirect page.

Source: https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html

Source code in aws_lambda_powertools/event_handler/openapi/swagger_ui/oauth2.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def generate_oauth2_redirect_html() -> str:
    """
    Generates the HTML content for the OAuth2 redirect page.

    Source: https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html
    """
    return """
<!doctype html>
<html lang="en-US">
<head>
    <title>Swagger UI: OAuth2 Redirect</title>
</head>
<body>
<script>
    'use strict';
    function run () {
        var oauth2 = window.opener.swaggerUIRedirectOauth2;
        var sentState = oauth2.state;
        var redirectUrl = oauth2.redirectUrl;
        var isValid, qp, arr;

        if (/code|token|error/.test(window.location.hash)) {
            qp = window.location.hash.substring(1).replace('?', '&');
        } else {
            qp = location.search.substring(1);
        }

        arr = qp.split("&");
        arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';});
        qp = qp ? JSON.parse('{' + arr.join() + '}',
                function (key, value) {
                    return key === "" ? value : decodeURIComponent(value);
                }
        ) : {};

        isValid = qp.state === sentState;

        if ((
          oauth2.auth.schema.get("flow") === "accessCode" ||
          oauth2.auth.schema.get("flow") === "authorizationCode" ||
          oauth2.auth.schema.get("flow") === "authorization_code"
        ) && !oauth2.auth.code) {
            if (!isValid) {
                oauth2.errCb({
                    authId: oauth2.auth.name,
                    source: "auth",
                    level: "warning",
                    message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server."
                });
            }

            if (qp.code) {
                delete oauth2.state;
                oauth2.auth.code = qp.code;
                oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
            } else {
                let oauthErrorMsg;
                if (qp.error) {
                    oauthErrorMsg = "["+qp.error+"]: " +
                        (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
                        (qp.error_uri ? "More info: "+qp.error_uri : "");
                }

                oauth2.errCb({
                    authId: oauth2.auth.name,
                    source: "auth",
                    level: "error",
                    message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server."
                });
            }
        } else {
            oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
        }
        window.close();
    }

    if (document.readyState !== 'loading') {
        run();
    } else {
        document.addEventListener('DOMContentLoaded', function () {
            run();
        });
    }
</script>
</body>
</html>
    """.strip()