Skip to content

OpenAPI

add_response(operation, status_code, schema, description, example=None, examples=None, links=None, content_type='application/json')

Add response to operation.

Version changed: 1.3.0

  • Add parameter content_type.

Version changed: 0.10.0

  • Add links parameter.
Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
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
def add_response(
    operation: dict,
    status_code: str,
    schema: t.Union[SchemaType, dict],
    description: str,
    example: t.Optional[t.Any] = None,
    examples: t.Optional[t.Dict[str, t.Any]] = None,
    links: t.Optional[t.Dict[str, t.Any]] = None,
    content_type: t.Optional[str] = 'application/json',
) -> None:
    """Add response to operation.

    *Version changed: 1.3.0*

    - Add parameter `content_type`.

    *Version changed: 0.10.0*

    - Add `links` parameter.
    """
    operation['responses'][status_code] = {}
    if status_code != '204':
        if isinstance(schema, FileSchema):
            schema = {'type': schema.type, 'format': schema.format}
        elif isinstance(schema, EmptySchema):
            schema = {}
        operation['responses'][status_code]['content'] = {
            content_type: {
                'schema': schema
            }
        }
    operation['responses'][status_code]['description'] = description
    if example is not None:
        operation['responses'][status_code]['content'][
            content_type]['example'] = example
    if examples is not None:
        operation['responses'][status_code]['content'][
            content_type]['examples'] = examples
    if links is not None:
        operation['responses'][status_code]['links'] = links

add_response_with_schema(spec, operation, status_code, schema, schema_name, description)

Add response with given schema to operation.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def add_response_with_schema(
    spec: APISpec,
    operation: dict,
    status_code: str,
    schema: OpenAPISchemaType,
    schema_name: str,
    description: str
) -> None:
    """Add response with given schema to operation."""
    if isinstance(schema, type):
        schema = schema()
        add_response(operation, status_code, schema, description)
    elif isinstance(schema, dict):
        if schema_name not in spec.components.schemas:
            spec.components.schema(schema_name, schema)
        schema_ref = {'$ref': f'#/components/schemas/{schema_name}'}
        add_response(operation, status_code, schema_ref, description)
    else:
        raise TypeError(_bad_schema_message)

get_argument(argument_type, argument_name)

Make argument from given type and name.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
224
225
226
227
228
229
230
231
232
233
234
235
236
def get_argument(argument_type: str, argument_name: str) -> t.Dict[str, t.Any]:
    """Make argument from given type and name."""
    argument: t.Dict[str, t.Any] = {
        'in': 'path',
        'name': argument_name,
    }
    if argument_type == 'int:':
        argument['schema'] = {'type': 'integer'}
    elif argument_type == 'float:':
        argument['schema'] = {'type': 'number'}
    else:
        argument['schema'] = {'type': 'string'}
    return argument

get_auth_name(auth, auth_names)

Get auth name from auth object.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
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
def get_auth_name(
    auth: HTTPAuthType,
    auth_names: t.List[str]
) -> str:
    """Get auth name from auth object."""
    name: str = ''
    if hasattr(auth, 'security_scheme_name'):
        name = auth.security_scheme_name  # type: ignore
    if not name:
        if isinstance(auth, HTTPBasicAuth):
            name = 'BasicAuth'
        elif isinstance(auth, HTTPTokenAuth):
            if auth.scheme.lower() == 'bearer' and auth.header is None:
                name = 'BearerAuth'
            else:
                name = 'ApiKeyAuth'
        else:
            raise TypeError('Unknown authentication scheme.')

    if name in auth_names:
        v = 2
        new_name = f'{name}_{v}'
        while new_name in auth_names:
            v += 1
            new_name = f'{name}_{v}'
        name = new_name
    return name

get_operation_tags(blueprint, blueprint_name)

Get operation tag from blueprint object.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def get_operation_tags(
    blueprint: APIBlueprint,
    blueprint_name: str
) -> t.List[str]:
    """Get operation tag from blueprint object."""
    tags: t.List[str]
    if blueprint.tag is not None:
        if isinstance(blueprint.tag, dict):
            tags = [blueprint.tag['name']]
        else:
            tags = [blueprint.tag]
    else:
        tags = [blueprint_name.title()]
    return tags

get_path_description(func)

Get path description from the docstring of the view function.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
152
153
154
155
156
157
158
def get_path_description(func: t.Callable) -> str:
    """Get path description from the docstring of the view function."""
    docs = (func.__doc__ or '').strip().split('\n')
    if len(docs) > 1:
        # use the remain lines of docstring as description
        return '\n'.join(docs[1:]).strip()
    return ''

get_path_summary(func, fallback=None)

Get path summary from the name or docstring of the view function.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
139
140
141
142
143
144
145
146
147
148
149
def get_path_summary(func: t.Callable, fallback: t.Optional[str] = None) -> str:
    """Get path summary from the name or docstring of the view function."""
    summary: str
    docs: list = (func.__doc__ or '').strip().split('\n')
    if docs[0]:
        # Use the first line of docstring
        summary = docs[0]
    else:
        # Use the function name
        summary = fallback or ' '.join(func.__name__.split('_')).title()
    return summary

get_security_and_security_schemes(auth_names, auth_schemes)

Make security and security schemes from given auth names and schemes.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
124
125
126
127
128
129
130
131
132
133
134
135
136
def get_security_and_security_schemes(
    auth_names: t.List[str],
    auth_schemes: t.List[HTTPAuthType]
) -> t.Tuple[t.Dict[HTTPAuthType, str], t.Dict[str, t.Dict[str, str]]]:
    """Make security and security schemes from given auth names and schemes."""
    security: t.Dict[HTTPAuthType, str] = {}
    security_schemes: t.Dict[str, t.Dict[str, str]] = {}
    for name, auth in zip(auth_names, auth_schemes):  # noqa: B905
        security[auth] = name
        security_schemes[name] = get_security_scheme(auth)
        if hasattr(auth, 'description') and auth.description is not None:
            security_schemes[name]['description'] = auth.description
    return security, security_schemes

get_security_scheme(auth)

Get security scheme from auth object.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def get_security_scheme(auth: HTTPAuthType) -> t.Dict[str, t.Any]:
    """Get security scheme from auth object."""
    security_scheme: t.Dict[str, t.Any]
    if isinstance(auth, HTTPTokenAuth):
        if auth.scheme.lower() == 'bearer' and auth.header is None:
            security_scheme = {
                'type': 'http',
                'scheme': 'bearer',
            }
        else:
            security_scheme = {
                'type': 'apiKey',
                'name': auth.header,
                'in': 'header',
            }
    else:
        security_scheme = {
            'type': 'http',
            'scheme': 'basic',
        }
    return security_scheme

get_tag(blueprint, blueprint_name)

Get tag from blueprint object.

Source code in /opt/buildhome/python3.8/lib/python3.8/site-packages/apiflask/openapi.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def get_tag(
    blueprint: APIBlueprint,
    blueprint_name: str
) -> t.Dict[str, t.Any]:
    """Get tag from blueprint object."""
    tag: t.Dict[str, t.Any]
    if blueprint.tag is not None:
        if isinstance(blueprint.tag, dict):
            tag = blueprint.tag
        else:
            tag = {'name': blueprint.tag}
    else:
        tag = {'name': blueprint_name.title()}
    return tag