Generate REST API and OpenAPI documentation for your Flask project with automatic request/response validation using Pydantic models.
npx @tessl/cli install tessl/pypi-flask-openapi3@4.2.00
# Flask-OpenAPI3
1
2
Flask-OpenAPI3 is a Flask extension that automatically generates REST API documentation and OpenAPI specifications. It provides request/response validation using Pydantic models, supports multiple OpenAPI UI templates, and follows the OpenAPI Specification 3.1.0 standard.
3
4
## Package Information
5
6
- **Package Name**: flask-openapi3
7
- **Language**: Python
8
- **Installation**: `pip install flask-openapi3`
9
10
## Core Imports
11
12
```python
13
from flask_openapi3 import OpenAPI
14
```
15
16
Working with blueprints and views:
17
18
```python
19
from flask_openapi3 import APIBlueprint, APIView
20
```
21
22
Common model imports:
23
24
```python
25
from flask_openapi3 import Info, Tag, Server
26
from flask_openapi3 import ValidationErrorModel, UnprocessableEntity
27
from flask_openapi3 import validate_request
28
```
29
30
All available model imports:
31
32
```python
33
from flask_openapi3 import (
34
APISpec, Components, Contact, Discriminator, Encoding, Example,
35
ExternalDocumentation, FileStorage, Header, License, Link, MediaType,
36
OAuthConfig, OAuthFlow, OAuthFlows, Operation, Parameter, ParameterInType,
37
PathItem, RawModel, Reference, RequestBody, Response, Schema,
38
SecurityScheme, ServerVariable, StyleValues, XML
39
)
40
```
41
42
## Basic Usage
43
44
```python
45
from flask_openapi3 import OpenAPI, Info
46
from pydantic import BaseModel
47
48
# Create OpenAPI app with metadata
49
info = Info(title="My API", version="1.0.0")
50
app = OpenAPI(__name__, info=info)
51
52
# Define request/response models
53
class UserQuery(BaseModel):
54
name: str
55
age: int = None
56
57
class UserResponse(BaseModel):
58
id: int
59
name: str
60
age: int
61
62
# Create API endpoint with automatic validation
63
@app.post("/users", responses={200: UserResponse})
64
def create_user(query: UserQuery):
65
"""Create a new user"""
66
# Request automatically validated against UserQuery
67
return {"id": 1, "name": query.name, "age": query.age or 25}
68
69
if __name__ == "__main__":
70
app.run(debug=True)
71
```
72
73
## Architecture
74
75
Flask-OpenAPI3 extends Flask with automatic OpenAPI specification generation:
76
77
- **OpenAPI Class**: Main Flask application with OpenAPI capabilities
78
- **APIBlueprint**: Flask Blueprint with automatic documentation
79
- **APIView**: Class-based views for organizing endpoints
80
- **Pydantic Models**: Define request/response schemas and validation
81
- **Validation System**: Automatic request validation and error handling
82
- **UI Templates**: Multiple documentation interfaces (Swagger, Redoc, RapiDoc, etc.)
83
84
The library integrates seamlessly with Flask's routing and error handling while adding comprehensive API documentation and validation capabilities.
85
86
## Capabilities
87
88
### Core Application Classes
89
90
The main classes for building OpenAPI-enabled Flask applications, including the primary OpenAPI class, blueprint system, and class-based views.
91
92
```python { .api }
93
class OpenAPI:
94
def __init__(
95
self,
96
import_name: str,
97
*,
98
info: Optional[Info] = None,
99
security_schemes: Optional[SecuritySchemesDict] = None,
100
responses: Optional[ResponseDict] = None,
101
servers: Optional[list[Server]] = None,
102
external_docs: Optional[ExternalDocumentation] = None,
103
operation_id_callback: Callable = get_operation_id_for_path,
104
openapi_extensions: Optional[dict[str, Any]] = None,
105
validation_error_status: Union[str, int] = 422,
106
validation_error_model: Type[BaseModel] = ValidationErrorModel,
107
validation_error_callback: Callable = make_validation_error_response,
108
doc_ui: bool = True,
109
doc_prefix: str = "/openapi",
110
doc_url: str = "/openapi.json",
111
**kwargs: Any
112
): ...
113
114
class APIBlueprint:
115
def __init__(
116
self,
117
name: str,
118
import_name: str,
119
*,
120
abp_tags: Optional[list[Tag]] = None,
121
abp_security: Optional[list[dict[str, list[str]]]] = None,
122
abp_responses: Optional[ResponseDict] = None,
123
doc_ui: bool = True,
124
operation_id_callback: Callable = get_operation_id_for_path,
125
**kwargs: Any
126
): ...
127
128
class APIView:
129
def __init__(
130
self,
131
url_prefix: Optional[str] = None,
132
view_tags: Optional[list[Tag]] = None,
133
view_security: Optional[list[dict[str, list[str]]]] = None,
134
view_responses: Optional[ResponseDict] = None,
135
doc_ui: bool = True,
136
operation_id_callback: Callable = get_operation_id_for_path,
137
): ...
138
```
139
140
[Core Application Classes](./core-classes.md)
141
142
### OpenAPI Models
143
144
Complete set of Pydantic models representing all OpenAPI 3.1.0 specification components, including API metadata, operation definitions, parameter specifications, and schema objects.
145
146
```python { .api }
147
class Info(BaseModel):
148
title: str
149
version: str
150
description: Optional[str] = None
151
termsOfService: Optional[str] = None
152
contact: Optional[Contact] = None
153
license: Optional[License] = None
154
155
class Tag(BaseModel):
156
name: str
157
description: Optional[str] = None
158
externalDocs: Optional[ExternalDocumentation] = None
159
160
class Server(BaseModel):
161
url: str
162
description: Optional[str] = None
163
variables: Optional[dict[str, ServerVariable]] = None
164
165
class Parameter(BaseModel):
166
name: str
167
in_: ParameterInType = Field(..., alias="in")
168
description: Optional[str] = None
169
required: bool = False
170
deprecated: bool = False
171
allowEmptyValue: bool = False
172
style: Optional[StyleValues] = None
173
explode: Optional[bool] = None
174
allowReserved: bool = False
175
schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema")
176
example: Optional[Any] = None
177
examples: Optional[dict[str, Union[Example, Reference]]] = None
178
```
179
180
[OpenAPI Models](./openapi-models.md)
181
182
### Request Validation
183
184
Automatic request validation using Pydantic models for different parameter types including path, query, header, cookie, form data, and request body validation.
185
186
```python { .api }
187
def validate_request():
188
"""
189
Decorator for automatic request validation against Pydantic models.
190
191
Applied automatically when using typed parameters in route handlers.
192
Validates path, query, header, cookie, form, and body parameters.
193
"""
194
195
# Internal validation functions
196
def _validate_request(
197
path: Optional[Type[BaseModel]] = None,
198
query: Optional[Type[BaseModel]] = None,
199
header: Optional[Type[BaseModel]] = None,
200
cookie: Optional[Type[BaseModel]] = None,
201
form: Optional[Type[BaseModel]] = None,
202
body: Optional[Type[BaseModel]] = None,
203
raw: Optional[Type[RawModel]] = None
204
) -> Callable: ...
205
```
206
207
[Request Validation](./validation.md)
208
209
### Utility Functions
210
211
Helper functions for OpenAPI specification generation, parameter parsing, schema extraction, and operation management.
212
213
```python { .api }
214
def get_operation(
215
func: Callable,
216
*,
217
summary: Optional[str] = None,
218
description: Optional[str] = None,
219
openapi_extensions: Optional[dict[str, Any]] = None,
220
) -> Operation: ...
221
222
def get_operation_id_for_path(
223
*,
224
bp_name: str = "",
225
name: str = "",
226
path: str = "",
227
method: str = ""
228
) -> str: ...
229
230
def get_model_schema(
231
model: Type[BaseModel],
232
mode: JsonSchemaMode = "validation"
233
) -> dict: ...
234
235
def parse_parameters(
236
path: Optional[Type[BaseModel]] = None,
237
query: Optional[Type[BaseModel]] = None,
238
header: Optional[Type[BaseModel]] = None,
239
cookie: Optional[Type[BaseModel]] = None,
240
form: Optional[Type[BaseModel]] = None,
241
body: Optional[Type[BaseModel]] = None,
242
raw: Optional[Type[RawModel]] = None
243
) -> ParametersTuple: ...
244
```
245
246
[Utility Functions](./utilities.md)
247
248
### CLI Commands
249
250
Command-line interface for exporting OpenAPI specifications in JSON or YAML format.
251
252
```python { .api }
253
@click.command(name="openapi")
254
@click.option("--output", "-o", type=click.Path(), help="The output file path.")
255
@click.option("--format", "-f", "_format", type=click.Choice(["json", "yaml"]), help="The output file format.")
256
@click.option("--indent", "-i", type=int, help="The indentation for JSON dumps.")
257
@with_appcontext
258
def openapi_command(output, _format, indent):
259
"""Export the OpenAPI Specification to console or a file"""
260
```
261
262
[CLI Commands](./cli-commands.md)
263
264
## Types
265
266
### Core Type Aliases
267
268
```python { .api }
269
ResponseDict = dict[Union[str, int, HTTPStatus], Union[Type[BaseModel], dict[Any, Any], None]]
270
SecuritySchemesDict = dict[str, Union[SecurityScheme, dict[str, Any]]]
271
ParametersTuple = tuple[
272
Optional[Type[BaseModel]], # path
273
Optional[Type[BaseModel]], # query
274
Optional[Type[BaseModel]], # header
275
Optional[Type[BaseModel]], # cookie
276
Optional[Type[BaseModel]], # form
277
Optional[Type[BaseModel]], # body
278
Optional[Type[RawModel]] # raw
279
]
280
```
281
282
### Enums
283
284
```python { .api }
285
class ParameterInType(str, Enum):
286
query = "query"
287
header = "header"
288
path = "path"
289
cookie = "cookie"
290
291
class HTTPMethod(str, Enum):
292
GET = "GET"
293
POST = "POST"
294
PUT = "PUT"
295
DELETE = "DELETE"
296
PATCH = "PATCH"
297
HEAD = "HEAD"
298
OPTIONS = "OPTIONS"
299
TRACE = "TRACE"
300
CONNECT = "CONNECT"
301
302
class StyleValues(str, Enum):
303
matrix = "matrix"
304
label = "label"
305
form = "form"
306
simple = "simple"
307
spaceDelimited = "spaceDelimited"
308
pipeDelimited = "pipeDelimited"
309
deepObject = "deepObject"
310
```
311
312
## Constants
313
314
```python { .api }
315
HTTP_STATUS: dict[str, str] # HTTP status code to phrase mapping
316
OPENAPI3_REF_PREFIX: str = "#/components/schemas"
317
OPENAPI3_REF_TEMPLATE: str = "#/components/schemas/{model}"
318
```