Fully featured framework for fast, easy and documented API development with Flask
npx @tessl/cli install tessl/pypi-flask-restx@1.3.0Flask-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.
pip install flask-restxfrom flask_restx import Api, Resource, NamespaceCommon imports for building APIs:
from flask_restx import Api, Resource, Namespace, fields, reqparseFull feature set:
from flask_restx import (
Api, Resource, Namespace, Model, OrderedModel, SchemaModel,
fields, reqparse, inputs, marshal, marshal_with, marshal_with_field,
Mask, Swagger, abort, RestError, ValidationError, SpecsError,
cors, apidoc, __version__, __description__
)Sub-module imports:
from flask_restx import fields, reqparse, inputs, cors
from flask_restx.marshalling import marshal, marshal_with, marshal_with_field
from flask_restx.mask import Mask
from flask_restx.errors import abort, RestError, ValidationError, SpecsError
from flask_restx.swagger import Swaggerfrom flask import Flask
from flask_restx import Api, Resource, fields
app = Flask(__name__)
api = Api(app, version='1.0', title='My API', description='A simple API')
# Define a namespace
ns = api.namespace('hello', description='Hello operations')
# Define a model for response marshalling
hello_model = api.model('Hello', {
'message': fields.String(required=True, description='The greeting message'),
'timestamp': fields.DateTime(required=True, description='When the greeting was generated')
})
@ns.route('/<string:name>')
class HelloWorld(Resource):
@ns.marshal_with(hello_model)
@ns.doc('get_hello')
def get(self, name):
"""Fetch a personalized greeting"""
from datetime import datetime
return {
'message': f'Hello {name}!',
'timestamp': datetime.utcnow()
}
if __name__ == '__main__':
app.run(debug=True)Flask-RESTX builds on Flask's foundation with several key components:
The framework emphasizes documentation-driven development, automatically generating comprehensive Swagger/OpenAPI documentation from code annotations and type definitions.
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.
class Api:
def __init__(
self,
app=None,
version="1.0",
title=None,
description=None,
terms_url=None,
license=None,
license_url=None,
contact=None,
contact_url=None,
contact_email=None,
authorizations=None,
security=None,
doc="/",
default_id=None,
default="default",
default_label="Default namespace",
validate=None,
tags=None,
prefix="",
ordered=False,
default_mediatype="application/json",
decorators=None,
catch_all_404s=False,
serve_challenge_on_401=False,
format_checker=None,
url_scheme=None,
default_swagger_filename="swagger.json",
**kwargs
): ...
def init_app(self, app, **kwargs): ...
def namespace(self, name, description=None, path=None, **kwargs): ...
def add_namespace(self, ns, path=None): ...
def route(self, *urls, **kwargs): ...
def marshal_with(self, fields, **kwargs): ...
def expect(self, *inputs, **kwargs): ...
def doc(self, shortcut=None, **kwargs): ...
def hide(self, func): ...
def deprecated(self, func): ...
def param(self, name, description=None, _in='query', **kwargs): ...
def response(self, code=200, description='Success', model=None, **kwargs): ...
def header(self, name, description=None, **kwargs): ...
def produces(self, mimetypes): ...
def errorhandler(self, exception): ...
def representation(self, mediatype): ...
def as_postman(self, urlvars=False, swagger=False): ...
def url_for(self, resource, **values): ...
def model(self, name=None, model=None, mask=None, strict=False, **kwargs): ...
def schema_model(self, name=None, schema=None): ...
def clone(self, name, *specs): ...
def inherit(self, name, *specs): ...
def parser(self): ...
def abort(self, *args, **kwargs): ...
@property
def specs_url(self): ...
@property
def base_url(self): ...
@property
def base_path(self): ...
@property
def payload(self): ...
class Resource:
def __init__(self, api=None, *args, **kwargs): ...
def dispatch_request(self, *args, **kwargs): ...
class Namespace:
def __init__(
self,
name,
description=None,
path=None,
decorators=None,
validate=None,
authorizations=None,
ordered=False,
**kwargs
): ...
def add_resource(self, resource, *urls, **kwargs): ...
def route(self, *urls, **kwargs): ...
def marshal_with(self, fields, **kwargs): ...
def marshal_list_with(self, fields, **kwargs): ...
def expect(self, *inputs, **kwargs): ...
def doc(self, shortcut=None, **kwargs): ...
def hide(self, func): ...
def deprecated(self, func): ...
def param(self, name, description=None, _in='query', **kwargs): ...
def response(self, code=200, description='Success', model=None, **kwargs): ...
def header(self, name, description=None, **kwargs): ...
def produces(self, mimetypes): ...
def errorhandler(self, exception): ...
def model(self, name=None, model=None, mask=None, strict=False, **kwargs): ...
def schema_model(self, name=None, schema=None): ...
def clone(self, name, *specs): ...
def inherit(self, name, *specs): ...
def parser(self): ...
def abort(self, *args, **kwargs): ...
def as_list(self, field): ...
def marshal(self, *args, **kwargs): ...
def vendor(self, *args, **kwargs): ...
@property
def path(self): ...
@property
def payload(self): ...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.
class RequestParser:
def __init__(
self,
argument_class=None,
result_class=None,
trim=False,
bundle_errors=False
): ...
def add_argument(
self,
name,
default=None,
dest=None,
required=False,
ignore=False,
type=str,
location=("json", "values"),
choices=(),
action='store',
help=None,
operators=('=',),
case_sensitive=True,
store_missing=True,
trim=False,
nullable=True
): ...
def parse_args(self, req=None, strict=False): ...
def copy(self): ...
def replace_argument(self, name, **kwargs): ...
def remove_argument(self, name): ...
class Argument:
def __init__(
self,
name,
default=None,
dest=None,
required=False,
ignore=False,
type=str,
location=("json", "values"),
choices=(),
action='store',
help=None,
operators=('=',),
case_sensitive=True,
store_missing=True,
trim=False,
nullable=True
): ...
# Input validation functions
def boolean(value): ...
def date_from_iso8601(value): ...
def datetime_from_iso8601(value): ...
def datetime_from_rfc822(value): ...
def ipv4(value): ...
def ipv6(value): ...
def ip(value): ...
def natural(value, argument="argument"): ...
def positive(value, argument="argument"): ...
def date(value): ...
def iso8601interval(value, argument="argument"): ...
# Input validation classes
class regex:
def __init__(self, pattern): ...
class int_range:
def __init__(self, low, high, argument="argument"): ...
class URL:
def __init__(self, check=False, ip=False, local=False, port=False, auth=False, schemes=None, domains=None, exclude=None): ...
class email:
def __init__(self, check=False, ip=False, local=False, domains=None, exclude=None): ...Request Parsing and Validation
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.
def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=False): ...
def marshal_with(fields, **kwargs): ...
def marshal_with_field(field, **kwargs): ...
# Core field types
class Raw: ...
class String: ...
class Integer: ...
class Float: ...
class Boolean: ...
class DateTime: ...
class Date: ...
class List: ...
class Nested: ...
class Url: ...
class FormattedString: ...
class ClassName: ...
class Arbitrary: ...
class Fixed: ...
class Polymorph: ...
class Wildcard: ...Response Marshalling and Fields
Schema definition system for complex data structures with JSON Schema validation, inheritance support, and automatic documentation generation. Enables declarative API contracts with comprehensive validation.
class Model:
def __init__(self, name, *args, **kwargs): ...
def inherit(self, name, *parents): ...
def validate(self, data, resolver=None, format_checker=None): ...
class OrderedModel: ...
class SchemaModel: ...
class Mask:
def __init__(self, mask=None, skip=False, **kwargs): ...
def parse(self, mask): ...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.
def abort(code=500, message=None, **kwargs): ...
class RestError(Exception): ...
class ValidationError(RestError): ...
class SpecsError(RestError): ...
def crossdomain(
origin=None,
methods=None,
headers=None,
expose_headers=None,
max_age=21600,
attach_to_all=True,
automatic_options=True,
credentials=False
): ...
class Swagger:
def __init__(self, api): ...
def as_dict(self): ...
@property
def paths(self): ...
@property
def definitions(self): ...
@property
def tags(self): ...
# HTTP Status constants
class HTTPStatus: ...
# Utility functions
def output_json(data, code, headers=None): ...# Core type aliases and constants used across the framework
from typing import Any, Dict, List, Optional, Tuple, Union, Callable
from enum import IntEnum
from collections import OrderedDict
from werkzeug.datastructures import FileStorage
# HTTP status codes
HTTPStatus = IntEnum # Complete set of HTTP status codes with names and descriptions
# Response type for Resource methods
ResponseTuple = Union[
Any, # Response data only
Tuple[Any, int], # (data, status_code)
Tuple[Any, int, Dict[str, str]], # (data, status_code, headers)
Tuple[Any, Dict[str, str]] # (data, headers)
]
# Field mask type for filtering responses
MaskType = Union[str, Dict[str, Any], 'Mask']
# Model validation result
ValidationResult = Dict[str, Any]
# Field definition type
FieldType = Union['Raw', Dict[str, 'Raw']]
# Request parser location types
LocationType = Union[str, List[str], Tuple[str, ...]]
# Argument types for request parsing
ArgumentType = Union[str, int, float, bool, FileStorage, Callable]
# Model types
ModelType = Union['Model', 'OrderedModel', 'SchemaModel', Dict[str, FieldType]]
# Decorator type for API functions
DecoratorType = Callable[[Callable], Callable]
# Configuration dictionary type
ConfigType = Dict[str, Any]
# Swagger specification type
SwaggerSpec = Dict[str, Any]
# Error response type
ErrorResponse = Dict[str, Union[str, int, Dict]]