0
# Application Classes
1
2
Core application classes for creating Connexion-based web services. These classes provide different underlying frameworks and deployment models while maintaining a consistent interface for OpenAPI-driven development.
3
4
## Capabilities
5
6
### AsyncApp
7
8
Native asynchronous ASGI application providing the best performance and modern Python async/await support. Recommended for new projects.
9
10
```python { .api }
11
class AsyncApp:
12
def __init__(
13
self,
14
import_name: str,
15
*,
16
lifespan=None,
17
middlewares=None,
18
specification_dir: Union[pathlib.Path, str] = "",
19
arguments: dict = None,
20
auth_all_paths: bool = None,
21
jsonifier=None,
22
pythonic_params: bool = None,
23
resolver=None,
24
resolver_error: int = None,
25
strict_validation: bool = None,
26
swagger_ui_options=None,
27
uri_parser_class=None,
28
validate_responses: bool = None,
29
validator_map: dict = None,
30
security_map: dict = None
31
):
32
"""
33
Create a new AsyncApp instance.
34
35
Parameters:
36
- import_name: Name of the application module
37
- lifespan: ASGI lifespan handler
38
- middlewares: List of additional middlewares
39
- specification_dir: Directory containing OpenAPI specs
40
- arguments: Global arguments for spec templating
41
- auth_all_paths: Whether to authenticate all paths
42
- jsonifier: Custom JSON serializer
43
- pythonic_params: Convert parameter names to pythonic style
44
- resolver: Custom operation resolver
45
- resolver_error: Error code for unresolved operations
46
- strict_validation: Enable strict validation mode
47
- swagger_ui_options: SwaggerUI configuration options
48
- uri_parser_class: Custom URI parser class
49
- validate_responses: Enable response validation
50
- validator_map: Custom validator mapping
51
- security_map: Custom security handler mapping
52
"""
53
54
def add_api(
55
self,
56
specification: Union[pathlib.Path, str, dict],
57
*,
58
base_path: str = None,
59
name: str = None,
60
arguments: dict = None,
61
auth_all_paths: bool = None,
62
jsonifier=None,
63
pythonic_params: bool = None,
64
resolver=None,
65
resolver_error: int = None,
66
strict_validation: bool = None,
67
swagger_ui_options=None,
68
uri_parser_class=None,
69
validate_responses: bool = None,
70
validator_map: dict = None,
71
security_map: dict = None,
72
**kwargs
73
):
74
"""
75
Add an OpenAPI specification to the application.
76
77
Parameters:
78
- specification: OpenAPI specification as path, dict, or URL
79
- base_path: Override base path from spec
80
- name: Name to register the API with
81
- arguments: Arguments for spec templating
82
- auth_all_paths: Authenticate all paths override
83
- jsonifier: Custom JSON serializer override
84
- pythonic_params: Pythonic params override
85
- resolver: Custom operation resolver
86
- resolver_error: Error code for unresolved operations
87
- strict_validation: Strict validation override
88
- swagger_ui_options: SwaggerUI configuration options
89
- uri_parser_class: Custom URI parser override
90
- validate_responses: Response validation override
91
- validator_map: Custom validator mapping
92
- security_map: Custom security handler mapping
93
- **kwargs: Additional keyword arguments
94
95
Returns:
96
AsyncApi instance
97
"""
98
99
def run(
100
self,
101
host: str = None,
102
port: int = None,
103
debug: bool = None,
104
**options
105
):
106
"""
107
Run the application with uvicorn development server.
108
109
Parameters:
110
- host: Server host (default: 127.0.0.1)
111
- port: Server port (default: 5000)
112
- debug: Debug mode override
113
- **options: Additional uvicorn options
114
"""
115
116
async def __call__(self, scope: dict, receive, send):
117
"""ASGI application callable interface."""
118
```
119
120
### FlaskApp
121
122
Flask-based WSGI application providing compatibility with Flask ecosystem and traditional deployment models.
123
124
```python { .api }
125
class FlaskApp:
126
def __init__(
127
self,
128
import_name: str,
129
instance_relative_config: bool = False,
130
middlewares=None,
131
specification_dir: str = "",
132
arguments: dict = None,
133
auth_all_paths: bool = False,
134
jsonifier=None,
135
pythonic_params: bool = False,
136
options=None,
137
strict_validation: bool = False,
138
validate_responses: bool = False,
139
uri_parser_class=None,
140
debug: bool = False
141
):
142
"""
143
Create a new FlaskApp instance.
144
145
Parameters follow same pattern as AsyncApp with additional:
146
- instance_relative_config: Enable Flask instance-relative config
147
"""
148
149
def add_api(
150
self,
151
specification: Union[pathlib.Path, str, dict],
152
*,
153
base_path: str = None,
154
name: str = None,
155
arguments: dict = None,
156
auth_all_paths: bool = None,
157
jsonifier=None,
158
pythonic_params: bool = None,
159
resolver=None,
160
resolver_error: int = None,
161
strict_validation: bool = None,
162
swagger_ui_options=None,
163
uri_parser_class=None,
164
validate_responses: bool = None,
165
validator_map: dict = None,
166
security_map: dict = None,
167
**kwargs
168
):
169
"""
170
Add an OpenAPI specification to the Flask application.
171
Parameters match AsyncApp.add_api().
172
173
Returns:
174
FlaskApi instance
175
"""
176
177
def run(
178
self,
179
host: str = None,
180
port: int = None,
181
debug: bool = None,
182
load_dotenv: bool = True,
183
**options
184
):
185
"""
186
Run the Flask development server.
187
188
Parameters:
189
- host: Server host (default: 127.0.0.1)
190
- port: Server port (default: 5000)
191
- debug: Debug mode override
192
- load_dotenv: Load environment from .env file
193
- **options: Additional Flask run options
194
"""
195
196
@property
197
def app(self):
198
"""Access to underlying Flask application instance."""
199
```
200
201
### ConnexionMiddleware
202
203
ASGI middleware for adding Connexion functionality to existing ASGI applications.
204
205
```python { .api }
206
class ConnexionMiddleware:
207
def __init__(
208
self,
209
app,
210
*,
211
import_name: str = None,
212
lifespan=None,
213
middlewares=None,
214
specification_dir: Union[pathlib.Path, str] = "",
215
arguments: dict = None,
216
auth_all_paths: bool = None,
217
jsonifier=None,
218
pythonic_params: bool = None,
219
resolver=None,
220
resolver_error: int = None,
221
strict_validation: bool = None,
222
swagger_ui_options=None,
223
uri_parser_class=None,
224
validate_responses: bool = None,
225
validator_map: dict = None,
226
security_map: dict = None
227
):
228
"""
229
Wrap an existing ASGI application with Connexion middleware.
230
231
Parameters:
232
- app: ASGI application to wrap
233
- import_name: Name of the application module
234
- lifespan: ASGI lifespan handler
235
- middlewares: List of additional middlewares
236
- specification_dir: Directory containing OpenAPI specs
237
- arguments: Global arguments for spec templating
238
- auth_all_paths: Whether to authenticate all paths
239
- jsonifier: Custom JSON serializer
240
- pythonic_params: Convert parameter names to pythonic style
241
- resolver: Custom operation resolver
242
- resolver_error: Error code for unresolved operations
243
- strict_validation: Enable strict validation mode
244
- swagger_ui_options: SwaggerUI configuration options
245
- uri_parser_class: Custom URI parser class
246
- validate_responses: Enable response validation
247
- validator_map: Custom validator mapping
248
- security_map: Custom security handler mapping
249
"""
250
251
def add_api(
252
self,
253
specification: Union[pathlib.Path, str, dict],
254
*,
255
base_path: str = None,
256
name: str = None,
257
arguments: dict = None,
258
auth_all_paths: bool = None,
259
jsonifier=None,
260
pythonic_params: bool = None,
261
resolver=None,
262
resolver_error: int = None,
263
strict_validation: bool = None,
264
swagger_ui_options=None,
265
uri_parser_class=None,
266
validate_responses: bool = None,
267
validator_map: dict = None,
268
security_map: dict = None,
269
**kwargs
270
):
271
"""Add OpenAPI specification to middleware.
272
Parameters match AsyncApp.add_api()."""
273
274
async def __call__(self, scope: dict, receive, send):
275
"""ASGI middleware callable interface."""
276
```
277
278
### AbstractApp
279
280
Base class for all Connexion applications providing common interface and functionality.
281
282
```python { .api }
283
class AbstractApp:
284
def __init__(self, import_name: str, **kwargs):
285
"""Base application initialization."""
286
287
def add_api(self, specification: str, **kwargs):
288
"""Abstract method for adding OpenAPI specifications."""
289
290
def add_url_rule(
291
self,
292
rule: str,
293
endpoint: str = None,
294
view_func=None,
295
**options
296
):
297
"""
298
Add a URL routing rule.
299
300
Parameters:
301
- rule: URL rule pattern
302
- endpoint: Endpoint name
303
- view_func: View function to handle requests
304
- **options: Additional routing options
305
"""
306
307
def add_error_handler(
308
self,
309
code_or_exception,
310
function
311
):
312
"""
313
Add an error handler.
314
315
Parameters:
316
- code_or_exception: HTTP status code or exception class
317
- function: Error handler function
318
"""
319
320
def run(self, host: str = None, port: int = None, **options):
321
"""Abstract method for running the application."""
322
```
323
324
## Usage Examples
325
326
### Creating a Production AsyncApp
327
328
```python
329
from connexion import AsyncApp
330
from connexion.options import SwaggerUIOptions
331
332
# Configure Swagger UI
333
swagger_options = SwaggerUIOptions(
334
enabled=True,
335
path="/docs",
336
swagger_ui_bundle_js="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js",
337
swagger_ui_standalone_preset_js="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-standalone-preset.js"
338
)
339
340
# Create application with production settings
341
app = AsyncApp(
342
__name__,
343
specification_dir='specs/',
344
strict_validation=True,
345
validate_responses=True,
346
options=swagger_options,
347
pythonic_params=True
348
)
349
350
# Add API specification
351
app.add_api('api.yaml', strict_validation=True)
352
353
# Add custom error handler
354
def handle_404(exception):
355
return {"error": "Resource not found"}, 404
356
357
app.add_error_handler(404, handle_404)
358
```
359
360
### Flask Integration with Custom Options
361
362
```python
363
from connexion import FlaskApp
364
from connexion.resolver import RestyResolver
365
366
app = FlaskApp(__name__)
367
368
# Add API with custom resolver
369
app.add_api(
370
'petstore.yaml',
371
resolver=RestyResolver('api'),
372
pythonic_params=True,
373
strict_validation=True
374
)
375
376
# Access Flask app for additional configuration
377
flask_app = app.app
378
flask_app.config['SECRET_KEY'] = 'your-secret-key'
379
380
if __name__ == '__main__':
381
app.run(debug=True)
382
```
383
384
### Middleware Integration
385
386
```python
387
from connexion import ConnexionMiddleware
388
from starlette.applications import Starlette
389
from starlette.middleware.cors import CORSMiddleware
390
391
# Create base ASGI app
392
base_app = Starlette()
393
base_app.add_middleware(
394
CORSMiddleware,
395
allow_origins=["*"],
396
allow_methods=["*"],
397
allow_headers=["*"]
398
)
399
400
# Wrap with Connexion middleware
401
app = ConnexionMiddleware(base_app)
402
app.add_api('openapi.yaml')
403
```