Flask-RESTPlus
repository·master·Indexed 25 days ago
https://github.com/noirbizarre/flask-restplusA fully featured framework for fast, easy, and documented API development with Flask. It provides tools to build REST APIs with built-in Swagger documentation support, utilizing core components like Api, Namespace, and Resource. Key features include data model definition with Model and fields, serialization via marshal and marshal_with, request parsing with reqparse, and comprehensive error handling with custom decorators and abort helpers.
What's inside flask-restplus
- Flask-RESTPlus is a Flask extension designed for quickly building REST APIs. It provides a collection of decorators and tools to describe your API and automatically expose documentation using Swagger. It is designed to encourage best practices with minimal setup for developers familiar with Flask.
Important Notice: Flask-RESTPlus is unmaintained
masterIMPORTANT NOTICE
Flask-RESTPlus is considered unmaintained. The project has been forked to Flask-RESTX and will be maintained by the
python-restxorganization. It is recommended to use Flask-RESTX for new projects.Handle Werkzeug HTTPExceptions
masterWerkzeugHTTPExceptionobjects are automatically serialized by Flask-RESTPlus using theirdescriptionattribute. You can provide a custom message during instantiation or attach extra attributes to the exception object via the.dataattribute to include them in the JSON output.Skip None values in responses
masterTo reduce response size, you can skip fields that have a value of
Noneinstead of marshaling them as JSONnull.Use the
skip_none=Truekeyword argument in the@marshal_withdecorator.Note: If you are using
fields.Nested, you must also passskip_none=Trueto thefields.Nestedconstructor to ensure nested fields are also skipped when they areNone.from flask_restplus import Model, fields, marshal_with model = Model('Model', { 'name': fields.String, 'address_1': fields.String, 'address_2': fields.String }) @marshal_with(model, skip_none=True) def get(): return {'name': 'John', 'address_1': None} # Result: OrderedDict([('name', 'John')]) # For nested fields: model = Model('Model', { 'name': fields.String, 'location': fields.Nested(location_model, skip_none=True) })Configure OAuth2 Implicit Flow in Swagger UI
masterTo enable OAuth2 Implicit Flow for interactive testing within the Swagger UI, configure the following Flask app configs and provide the
authorizationsdictionary to theApiconstructor. Note thatclientIdis used instead of a client secret for this flow.from flask import Flask from flask_restplus import Api app = Flask(__name__) app.config.SWAGGER_UI_OAUTH_CLIENT_ID = 'MyClientId' app.config.SWAGGER_UI_OAUTH_REALM = '-' app.config.SWAGGER_UI_OAUTH_APP_NAME = 'Demo' api = Api( app, title=app.config.SWAGGER_UI_OAUTH_APP_NAME, security={'OAuth2': ['read', 'write']}, authorizations={ 'OAuth2': { 'type': 'oauth2', 'flow': 'implicit', 'authorizationUrl': 'https://idp.example.com/authorize?audience=https://app.example.com', 'clientId': app.config.SWAGGER_UI_OAUTH_CLIENT_ID, 'scopes': { 'openid': 'Get ID token', 'profile': 'Get identity', } } } )Document API authorizations
masterYou can document security requirements using the
authorizationsargument in theApiconstructor. This argument accepts a Python dictionary representing SwaggersecurityDefinitions.To apply security to specific resources or methods, use the
@api.doc(security='name')decorator. To apply security globally to all endpoints, use thesecurityparameter in theApiconstructor.To disable security for a specific method, pass
Noneor an empty list[]to thesecurityparameter in@api.doc().# 1. Define authorizations authorizations = { 'apikey': { 'type': 'apiKey', 'in': 'header', 'name': 'X-API-KEY' } } # 2. Initialize API (Global security or just definitions) api = Api(app, authorizations=authorizations, security='apikey') # 3. Decorate specific methods @api.route('/resource/') class Resource1(Resource): @api.doc(security='apikey') def get(self): pass @api.doc(security=[]) # Disable security for this method def post(self): passRun tests and quality checks with tox and inv qa
masterTo ensure your code is compliant with
flask-restplusstandards before committing, you should run both the quality report and thetoxtest suite.toxruns the test suite against all supported Python versions and ensures documentation generates correctly.inv qaensures code compliance with coding standards (PEP8 with a 120 character line length).You can run both simultaneously with a single command.
$ inv qa toxDocument errors in Swagger/OpenAPI
masterYou can document errors in your API documentation using several methods:
- Decorator approach: Combine
@api.errorhandlerwith@api.marshal_withand@api.headerto define the response schema and headers. - Docstring approach: For exceptions raised within a resource method, use the
:raises:docstring. Flask-RESTPlus will automatically extract this to document the error in Swagger.
Note: For OpenAPI 2.0 compliance, a 'NoResultFound' error with a description is required. The docstring of the error handler function is used as the description in
swagger.json.# Using decorators to document error response @api.errorhandler(FakeException) @api.marshal_with(error_fields, code=400) @api.header('My-Header', 'Some description') def handle_fake_exception_with_header(error): '''This is a custom error''' return {'message': error.message}, 400, {'My-Header': 'Value'} # Using docstrings to document raised exceptions @api.route('/test/') class TestResource(Resource): def get(self): ''' Do something :raises CustomException: In case of something ''' pass- Decorator approach: Combine
Install Flask-RESTPlus via pip
masterInstall the stable version of Flask-RESTPlus using
pip.pip install flask-restplusMaintain multiple API versions using Namespaces and Blueprints
masterTo support multiple API versions (e.g., v1 and v2), combine namespaces with Flask Blueprints. Create separate modules for each version (e.g.,apiv1.py,apiv2.py), each containing its ownApiinstance tied to a uniqueBlueprint. These versioned blueprints are then registered to the main Flask app.Install Flask-RESTPlus
masterYou can install Flask-RESTPlus using
piporeasy_install.$ pip install flask-restplusUse reqparse for request parsing
masterFlask-RESTPlus provides a
reqparsemodule modeled after Python'sargparseto provide uniform access to variables on theflask.requestobject.Note: This module is considered deprecated and slated for removal in version 2.0. It is recommended to consider integrating with packages like
marshmallowfor input/output handling. However, it will be maintained until 2.0.By default:
- Arguments are not required.
- Arguments not defined in the parser are ignored.
- Missing arguments default to
None. - The default argument type is a unicode string (
strin Python 3,unicodein Python 2).
from flask_restplus import reqparse parser = reqparse.RequestParser() parser.add_argument('rate', type=int, help='Rate cannot be converted') parser.add_argument('name') args = parser.parse_args()