0
# Core API Framework
1
2
The core API framework provides the fundamental classes and decorators for building REST APIs with Flask-RESTX. This includes the main Api class for managing the overall API, Resource class for individual endpoints, and Namespace system for organizing related functionality.
3
4
## Capabilities
5
6
### Api Class
7
8
The main entry point for creating REST APIs. Manages namespaces, global configuration, documentation generation, and request/response handling.
9
10
```python { .api }
11
class Api:
12
def __init__(
13
self,
14
app=None,
15
version="1.0",
16
title=None,
17
description=None,
18
terms_url=None,
19
license=None,
20
license_url=None,
21
contact=None,
22
contact_url=None,
23
contact_email=None,
24
authorizations=None,
25
security=None,
26
doc="/",
27
default_id=None,
28
default="default",
29
default_label="Default namespace",
30
validate=None,
31
tags=None,
32
prefix="",
33
ordered=False,
34
default_mediatype="application/json",
35
decorators=None,
36
catch_all_404s=False,
37
serve_challenge_on_401=False,
38
format_checker=None,
39
url_scheme=None,
40
default_swagger_filename="swagger.json",
41
**kwargs
42
):
43
"""
44
Initialize the API.
45
46
Parameters:
47
- app: Flask application or Blueprint
48
- version: API version for documentation (default: "1.0")
49
- title: API title for documentation
50
- description: API description for documentation
51
- terms_url: Terms of service URL
52
- license: License name
53
- license_url: License URL
54
- contact: Contact name
55
- contact_url: Contact URL
56
- contact_email: Contact email address
57
- authorizations: Swagger authorization definitions
58
- security: Default security requirements
59
- doc: Documentation path (default: "/")
60
- default_id: Default ID generator function
61
- default: Default namespace name (default: "default")
62
- default_label: Default namespace label
63
- validate: Enable input payload validation
64
- tags: List of API tags for documentation
65
- prefix: URL prefix for all routes
66
- ordered: Preserve order in models and marshalling
67
- default_mediatype: Default response media type
68
- decorators: List of decorators to apply to all resources
69
- catch_all_404s: Handle 404 errors with error handler
70
- serve_challenge_on_401: Serve basic auth challenge on 401
71
- format_checker: JSON schema format checker
72
- url_scheme: URL scheme override
73
- default_swagger_filename: Default Swagger spec filename
74
- kwargs: Additional arguments
75
"""
76
77
def init_app(self, app, **kwargs):
78
"""Initialize with Flask app (factory pattern)."""
79
80
def namespace(self, name, description=None, path=None, **kwargs):
81
"""Create and register a namespace."""
82
83
def add_namespace(self, ns, path=None):
84
"""Add an existing namespace to the API."""
85
86
def route(self, *urls, **kwargs):
87
"""Decorator to register resources directly on the API."""
88
89
def marshal_with(self, fields, **kwargs):
90
"""Decorator for automatic response marshalling."""
91
92
def expect(self, *inputs, **kwargs):
93
"""Decorator for input validation."""
94
95
def doc(self, shortcut=None, **kwargs):
96
"""Decorator to add documentation to endpoints."""
97
98
def hide(self, func):
99
"""Hide endpoint from documentation."""
100
101
def deprecated(self, func):
102
"""Mark endpoint as deprecated."""
103
104
def param(self, name, description=None, _in='query', **kwargs):
105
"""Document a parameter."""
106
107
def response(self, code=200, description='Success', model=None, **kwargs):
108
"""Document a response."""
109
110
def header(self, name, description=None, **kwargs):
111
"""Document a header."""
112
113
def produces(self, mimetypes):
114
"""Specify response media types."""
115
116
def errorhandler(self, exception):
117
"""Register an error handler."""
118
119
def representation(self, mediatype):
120
"""Register a response representation."""
121
122
def as_postman(self, urlvars=False, swagger=False):
123
"""Export API as Postman collection."""
124
125
def url_for(self, resource, **values):
126
"""Generate URL for a resource."""
127
128
def documentation(self, func):
129
"""Decorator for custom documentation view."""
130
131
def make_response(self, data, *args, **kwargs):
132
"""Create Flask response."""
133
134
def owns_endpoint(self, endpoint):
135
"""Check if endpoint belongs to this API."""
136
137
def handle_error(self, e):
138
"""Handle exceptions."""
139
140
def default_endpoint(self, resource, namespace):
141
"""Generate default endpoint name."""
142
143
def model(self, name=None, model=None, mask=None, strict=False, **kwargs):
144
"""Create and register a model."""
145
146
def schema_model(self, name=None, schema=None):
147
"""Create and register a schema model."""
148
149
def clone(self, name, *specs):
150
"""Clone model with additional fields."""
151
152
def inherit(self, name, *specs):
153
"""Create inherited model."""
154
155
def parser(self):
156
"""Create request parser."""
157
158
@property
159
def specs_url(self):
160
"""URL for API specification."""
161
162
@property
163
def base_url(self):
164
"""Base URL for API."""
165
166
@property
167
def base_path(self):
168
"""Base path for API."""
169
170
@property
171
def payload(self):
172
"""Current request payload."""
173
174
@property
175
def refresolver(self):
176
"""JSON schema resolver."""
177
178
@property
179
def __schema__(self):
180
"""Swagger schema."""
181
```
182
183
### Resource Class
184
185
Base class for API resources/endpoints. Extends Flask's MethodView to provide REST API functionality with automatic documentation and validation.
186
187
```python { .api }
188
class Resource:
189
def __init__(self, api=None, *args, **kwargs):
190
"""
191
Initialize the resource.
192
193
Parameters:
194
- api: Reference to the API instance
195
- args, kwargs: Additional arguments passed to MethodView
196
"""
197
198
def dispatch_request(self, *args, **kwargs):
199
"""Handle HTTP method dispatching with validation."""
200
201
def validate_payload(self, func):
202
"""Validate request payload against expected model."""
203
204
# Class attributes
205
representations = None # Custom representations
206
method_decorators = [] # Method decorators
207
208
# HTTP method handlers (implement as needed)
209
def get(self, *args, **kwargs):
210
"""Handle GET requests."""
211
212
def post(self, *args, **kwargs):
213
"""Handle POST requests."""
214
215
def put(self, *args, **kwargs):
216
"""Handle PUT requests."""
217
218
def patch(self, *args, **kwargs):
219
"""Handle PATCH requests."""
220
221
def delete(self, *args, **kwargs):
222
"""Handle DELETE requests."""
223
224
def head(self, *args, **kwargs):
225
"""Handle HEAD requests."""
226
227
def options(self, *args, **kwargs):
228
"""Handle OPTIONS requests."""
229
```
230
231
### Namespace Class
232
233
Groups related resources together with shared path prefix, decorators, and documentation. Similar to Flask Blueprints but specifically designed for REST APIs.
234
235
```python { .api }
236
class Namespace:
237
def __init__(
238
self,
239
name,
240
description=None,
241
path=None,
242
decorators=None,
243
validate=None,
244
authorizations=None,
245
ordered=False,
246
**kwargs
247
):
248
"""
249
Initialize the namespace.
250
251
Parameters:
252
- name: Namespace name
253
- description: Optional description
254
- path: URL path prefix (defaults to '/name')
255
- decorators: List of decorators for all resources
256
- validate: Enable validation for this namespace
257
- authorizations: Authorization definitions
258
- ordered: Preserve field order in models
259
- kwargs: Additional arguments including 'api' reference
260
"""
261
262
def add_resource(self, resource, *urls, **kwargs):
263
"""
264
Register a resource with URL routes.
265
266
Parameters:
267
- resource: Resource class to register
268
- urls: One or more URL routes
269
- kwargs: Additional Flask routing arguments
270
"""
271
272
def route(self, *urls, **kwargs):
273
"""Decorator to route resources."""
274
275
def doc(self, shortcut=None, **kwargs):
276
"""Decorator to add documentation."""
277
278
def hide(self, func):
279
"""Hide endpoint from documentation."""
280
281
def abort(self, *args, **kwargs):
282
"""Abort with namespace context."""
283
284
def marshal_with(self, fields, **kwargs):
285
"""Decorator for response marshalling."""
286
287
def marshal_list_with(self, fields, **kwargs):
288
"""Decorator for marshalling list responses."""
289
290
def marshal(self, *args, **kwargs):
291
"""Marshal data with fields."""
292
293
def expect(self, *inputs, **kwargs):
294
"""Decorator for input validation."""
295
296
def param(self, name, description=None, _in='query', **kwargs):
297
"""Document a parameter."""
298
299
def response(self, code=200, description='Success', model=None, **kwargs):
300
"""Document a response."""
301
302
def header(self, name, description=None, **kwargs):
303
"""Document a header."""
304
305
def produces(self, mimetypes):
306
"""Specify response media types."""
307
308
def deprecated(self, func):
309
"""Mark endpoint as deprecated."""
310
311
def vendor(self, *args, **kwargs):
312
"""Add vendor extensions."""
313
314
def errorhandler(self, exception):
315
"""Register error handler for this namespace."""
316
317
def as_list(self, field):
318
"""Wrap field as list for marshalling."""
319
320
def add_model(self, name, definition):
321
"""Register model with this namespace."""
322
323
def model(self, name=None, model=None, mask=None, strict=False, **kwargs):
324
"""Create and register a model."""
325
326
def schema_model(self, name=None, schema=None):
327
"""Create and register a schema model."""
328
329
def extend(self, name, parent, fields):
330
"""Extend model with additional fields (deprecated)."""
331
332
def clone(self, name, *specs):
333
"""Clone model with additional fields."""
334
335
def inherit(self, name, *specs):
336
"""Create inherited model."""
337
338
@property
339
def path(self):
340
"""Namespace URL path."""
341
342
@property
343
def parser(self):
344
"""Request parser instance."""
345
346
@property
347
def payload(self):
348
"""Current request payload."""
349
```
350
351
## Usage Examples
352
353
### Basic API Setup
354
355
```python
356
from flask import Flask
357
from flask_restx import Api, Resource
358
359
app = Flask(__name__)
360
api = Api(
361
app,
362
version='1.0',
363
title='My API',
364
description='A comprehensive REST API'
365
)
366
367
@api.route('/health')
368
class HealthCheck(Resource):
369
def get(self):
370
return {'status': 'healthy'}
371
```
372
373
### Using Namespaces
374
375
```python
376
from flask_restx import Namespace
377
378
# Create namespace
379
users_ns = api.namespace('users', description='User operations')
380
381
@users_ns.route('/')
382
class UserList(Resource):
383
def get(self):
384
return {'users': []}
385
386
def post(self):
387
return {'message': 'User created'}, 201
388
389
@users_ns.route('/<int:user_id>')
390
class User(Resource):
391
def get(self, user_id):
392
return {'user_id': user_id}
393
```
394
395
### Advanced Configuration
396
397
```python
398
# API with extensive configuration
399
api = Api(
400
app,
401
version='2.0',
402
title='Advanced API',
403
description='API with comprehensive configuration',
404
doc='/docs/', # Custom documentation path
405
catch_all_404s=True, # Handle 404s with API error handler
406
validate=True, # Enable validation by default
407
authorizations={
408
'Bearer': {
409
'type': 'apiKey',
410
'in': 'header',
411
'name': 'Authorization'
412
}
413
}
414
)
415
```