Fully featured framework for fast, easy and documented API development with Flask
npx @tessl/cli install tessl/pypi-flask-restx@1.3.00
# Flask-RESTX
1
2
Flask-RESTX is a comprehensive framework for building REST APIs with Flask. It provides a collection of decorators and tools to describe APIs and expose comprehensive documentation using Swagger/OpenAPI specification. The framework offers features for request parsing, response marshalling, input validation, error handling, namespacing, and automatic API documentation generation.
3
4
## Package Information
5
6
- **Package Name**: flask-restx
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install flask-restx`
10
11
## Core Imports
12
13
```python
14
from flask_restx import Api, Resource, Namespace
15
```
16
17
Common imports for building APIs:
18
19
```python
20
from flask_restx import Api, Resource, Namespace, fields, reqparse
21
```
22
23
Full feature set:
24
25
```python
26
from flask_restx import (
27
Api, Resource, Namespace, Model, OrderedModel, SchemaModel,
28
fields, reqparse, inputs, marshal, marshal_with, marshal_with_field,
29
Mask, Swagger, abort, RestError, ValidationError, SpecsError,
30
cors, apidoc, __version__, __description__
31
)
32
```
33
34
Sub-module imports:
35
36
```python
37
from flask_restx import fields, reqparse, inputs, cors
38
from flask_restx.marshalling import marshal, marshal_with, marshal_with_field
39
from flask_restx.mask import Mask
40
from flask_restx.errors import abort, RestError, ValidationError, SpecsError
41
from flask_restx.swagger import Swagger
42
```
43
44
## Basic Usage
45
46
```python
47
from flask import Flask
48
from flask_restx import Api, Resource, fields
49
50
app = Flask(__name__)
51
api = Api(app, version='1.0', title='My API', description='A simple API')
52
53
# Define a namespace
54
ns = api.namespace('hello', description='Hello operations')
55
56
# Define a model for response marshalling
57
hello_model = api.model('Hello', {
58
'message': fields.String(required=True, description='The greeting message'),
59
'timestamp': fields.DateTime(required=True, description='When the greeting was generated')
60
})
61
62
@ns.route('/<string:name>')
63
class HelloWorld(Resource):
64
@ns.marshal_with(hello_model)
65
@ns.doc('get_hello')
66
def get(self, name):
67
"""Fetch a personalized greeting"""
68
from datetime import datetime
69
return {
70
'message': f'Hello {name}!',
71
'timestamp': datetime.utcnow()
72
}
73
74
if __name__ == '__main__':
75
app.run(debug=True)
76
```
77
78
## Architecture
79
80
Flask-RESTX builds on Flask's foundation with several key components:
81
82
- **Api**: Main entry point that manages namespaces, documentation, and global configuration
83
- **Namespace**: Groups related resources together (similar to Flask Blueprints) with shared path prefix and documentation
84
- **Resource**: Base class for API endpoints that extends Flask's MethodView
85
- **Fields**: Type system for request/response validation and automatic documentation
86
- **Models**: Schema definitions for complex data structures with validation and documentation
87
- **RequestParser**: Declarative request parsing with automatic validation and documentation
88
89
The framework emphasizes documentation-driven development, automatically generating comprehensive Swagger/OpenAPI documentation from code annotations and type definitions.
90
91
## Capabilities
92
93
### Core API Framework
94
95
Main API management classes and decorators for building REST APIs with automatic documentation generation. Includes the primary Api class, Resource base class for endpoints, and Namespace system for organizing related functionality.
96
97
```python { .api }
98
class Api:
99
def __init__(
100
self,
101
app=None,
102
version="1.0",
103
title=None,
104
description=None,
105
terms_url=None,
106
license=None,
107
license_url=None,
108
contact=None,
109
contact_url=None,
110
contact_email=None,
111
authorizations=None,
112
security=None,
113
doc="/",
114
default_id=None,
115
default="default",
116
default_label="Default namespace",
117
validate=None,
118
tags=None,
119
prefix="",
120
ordered=False,
121
default_mediatype="application/json",
122
decorators=None,
123
catch_all_404s=False,
124
serve_challenge_on_401=False,
125
format_checker=None,
126
url_scheme=None,
127
default_swagger_filename="swagger.json",
128
**kwargs
129
): ...
130
def init_app(self, app, **kwargs): ...
131
def namespace(self, name, description=None, path=None, **kwargs): ...
132
def add_namespace(self, ns, path=None): ...
133
def route(self, *urls, **kwargs): ...
134
def marshal_with(self, fields, **kwargs): ...
135
def expect(self, *inputs, **kwargs): ...
136
def doc(self, shortcut=None, **kwargs): ...
137
def hide(self, func): ...
138
def deprecated(self, func): ...
139
def param(self, name, description=None, _in='query', **kwargs): ...
140
def response(self, code=200, description='Success', model=None, **kwargs): ...
141
def header(self, name, description=None, **kwargs): ...
142
def produces(self, mimetypes): ...
143
def errorhandler(self, exception): ...
144
def representation(self, mediatype): ...
145
def as_postman(self, urlvars=False, swagger=False): ...
146
def url_for(self, resource, **values): ...
147
def model(self, name=None, model=None, mask=None, strict=False, **kwargs): ...
148
def schema_model(self, name=None, schema=None): ...
149
def clone(self, name, *specs): ...
150
def inherit(self, name, *specs): ...
151
def parser(self): ...
152
def abort(self, *args, **kwargs): ...
153
@property
154
def specs_url(self): ...
155
@property
156
def base_url(self): ...
157
@property
158
def base_path(self): ...
159
@property
160
def payload(self): ...
161
162
class Resource:
163
def __init__(self, api=None, *args, **kwargs): ...
164
def dispatch_request(self, *args, **kwargs): ...
165
166
class Namespace:
167
def __init__(
168
self,
169
name,
170
description=None,
171
path=None,
172
decorators=None,
173
validate=None,
174
authorizations=None,
175
ordered=False,
176
**kwargs
177
): ...
178
def add_resource(self, resource, *urls, **kwargs): ...
179
def route(self, *urls, **kwargs): ...
180
def marshal_with(self, fields, **kwargs): ...
181
def marshal_list_with(self, fields, **kwargs): ...
182
def expect(self, *inputs, **kwargs): ...
183
def doc(self, shortcut=None, **kwargs): ...
184
def hide(self, func): ...
185
def deprecated(self, func): ...
186
def param(self, name, description=None, _in='query', **kwargs): ...
187
def response(self, code=200, description='Success', model=None, **kwargs): ...
188
def header(self, name, description=None, **kwargs): ...
189
def produces(self, mimetypes): ...
190
def errorhandler(self, exception): ...
191
def model(self, name=None, model=None, mask=None, strict=False, **kwargs): ...
192
def schema_model(self, name=None, schema=None): ...
193
def clone(self, name, *specs): ...
194
def inherit(self, name, *specs): ...
195
def parser(self): ...
196
def abort(self, *args, **kwargs): ...
197
def as_list(self, field): ...
198
def marshal(self, *args, **kwargs): ...
199
def vendor(self, *args, **kwargs): ...
200
@property
201
def path(self): ...
202
@property
203
def payload(self): ...
204
```
205
206
[Core API Framework](./core-api.md)
207
208
### Request Parsing and Validation
209
210
Declarative request parsing system that extracts and validates data from various request sources (query parameters, form data, JSON body, headers, files). Provides automatic validation, type conversion, and documentation generation.
211
212
```python { .api }
213
class RequestParser:
214
def __init__(
215
self,
216
argument_class=None,
217
result_class=None,
218
trim=False,
219
bundle_errors=False
220
): ...
221
def add_argument(
222
self,
223
name,
224
default=None,
225
dest=None,
226
required=False,
227
ignore=False,
228
type=str,
229
location=("json", "values"),
230
choices=(),
231
action='store',
232
help=None,
233
operators=('=',),
234
case_sensitive=True,
235
store_missing=True,
236
trim=False,
237
nullable=True
238
): ...
239
def parse_args(self, req=None, strict=False): ...
240
def copy(self): ...
241
def replace_argument(self, name, **kwargs): ...
242
def remove_argument(self, name): ...
243
244
class Argument:
245
def __init__(
246
self,
247
name,
248
default=None,
249
dest=None,
250
required=False,
251
ignore=False,
252
type=str,
253
location=("json", "values"),
254
choices=(),
255
action='store',
256
help=None,
257
operators=('=',),
258
case_sensitive=True,
259
store_missing=True,
260
trim=False,
261
nullable=True
262
): ...
263
264
# Input validation functions
265
def boolean(value): ...
266
def date_from_iso8601(value): ...
267
def datetime_from_iso8601(value): ...
268
def datetime_from_rfc822(value): ...
269
def ipv4(value): ...
270
def ipv6(value): ...
271
def ip(value): ...
272
def natural(value, argument="argument"): ...
273
def positive(value, argument="argument"): ...
274
def date(value): ...
275
def iso8601interval(value, argument="argument"): ...
276
277
# Input validation classes
278
class regex:
279
def __init__(self, pattern): ...
280
class int_range:
281
def __init__(self, low, high, argument="argument"): ...
282
class URL:
283
def __init__(self, check=False, ip=False, local=False, port=False, auth=False, schemes=None, domains=None, exclude=None): ...
284
class email:
285
def __init__(self, check=False, ip=False, local=False, domains=None, exclude=None): ...
286
```
287
288
[Request Parsing and Validation](./request-parsing.md)
289
290
### Response Marshalling and Fields
291
292
Type system for defining response schemas with automatic serialization, validation, and documentation. Provides comprehensive field types for primitive and complex data structures with extensive configuration options.
293
294
```python { .api }
295
def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=False): ...
296
def marshal_with(fields, **kwargs): ...
297
def marshal_with_field(field, **kwargs): ...
298
299
# Core field types
300
class Raw: ...
301
class String: ...
302
class Integer: ...
303
class Float: ...
304
class Boolean: ...
305
class DateTime: ...
306
class Date: ...
307
class List: ...
308
class Nested: ...
309
class Url: ...
310
class FormattedString: ...
311
class ClassName: ...
312
class Arbitrary: ...
313
class Fixed: ...
314
class Polymorph: ...
315
class Wildcard: ...
316
```
317
318
[Response Marshalling and Fields](./marshalling-fields.md)
319
320
### Models and Data Validation
321
322
Schema definition system for complex data structures with JSON Schema validation, inheritance support, and automatic documentation generation. Enables declarative API contracts with comprehensive validation.
323
324
```python { .api }
325
class Model:
326
def __init__(self, name, *args, **kwargs): ...
327
def inherit(self, name, *parents): ...
328
def validate(self, data, resolver=None, format_checker=None): ...
329
330
class OrderedModel: ...
331
class SchemaModel: ...
332
333
class Mask:
334
def __init__(self, mask=None, skip=False, **kwargs): ...
335
def parse(self, mask): ...
336
```
337
338
[Models and Data Validation](./models-validation.md)
339
340
### Error Handling and Utilities
341
342
Comprehensive error handling system with HTTP status code management, custom exception types, and CORS support. Provides utilities for API error responses and cross-origin resource sharing.
343
344
```python { .api }
345
def abort(code=500, message=None, **kwargs): ...
346
347
class RestError(Exception): ...
348
class ValidationError(RestError): ...
349
class SpecsError(RestError): ...
350
351
def crossdomain(
352
origin=None,
353
methods=None,
354
headers=None,
355
expose_headers=None,
356
max_age=21600,
357
attach_to_all=True,
358
automatic_options=True,
359
credentials=False
360
): ...
361
362
class Swagger:
363
def __init__(self, api): ...
364
def as_dict(self): ...
365
@property
366
def paths(self): ...
367
@property
368
def definitions(self): ...
369
@property
370
def tags(self): ...
371
372
# HTTP Status constants
373
class HTTPStatus: ...
374
375
# Utility functions
376
def output_json(data, code, headers=None): ...
377
```
378
379
[Error Handling and Utilities](./error-handling.md)
380
381
## Types
382
383
```python { .api }
384
# Core type aliases and constants used across the framework
385
from typing import Any, Dict, List, Optional, Tuple, Union, Callable
386
from enum import IntEnum
387
from collections import OrderedDict
388
from werkzeug.datastructures import FileStorage
389
390
# HTTP status codes
391
HTTPStatus = IntEnum # Complete set of HTTP status codes with names and descriptions
392
393
# Response type for Resource methods
394
ResponseTuple = Union[
395
Any, # Response data only
396
Tuple[Any, int], # (data, status_code)
397
Tuple[Any, int, Dict[str, str]], # (data, status_code, headers)
398
Tuple[Any, Dict[str, str]] # (data, headers)
399
]
400
401
# Field mask type for filtering responses
402
MaskType = Union[str, Dict[str, Any], 'Mask']
403
404
# Model validation result
405
ValidationResult = Dict[str, Any]
406
407
# Field definition type
408
FieldType = Union['Raw', Dict[str, 'Raw']]
409
410
# Request parser location types
411
LocationType = Union[str, List[str], Tuple[str, ...]]
412
413
# Argument types for request parsing
414
ArgumentType = Union[str, int, float, bool, FileStorage, Callable]
415
416
# Model types
417
ModelType = Union['Model', 'OrderedModel', 'SchemaModel', Dict[str, FieldType]]
418
419
# Decorator type for API functions
420
DecoratorType = Callable[[Callable], Callable]
421
422
# Configuration dictionary type
423
ConfigType = Dict[str, Any]
424
425
# Swagger specification type
426
SwaggerSpec = Dict[str, Any]
427
428
# Error response type
429
ErrorResponse = Dict[str, Union[str, int, Dict]]
430
```