Flask-RESTPlus

repository·master·Indexed 25 days ago

https://github.com/noirbizarre/flask-restplus

A 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.

Tokens
18.3K
Snippets
62
Records
83
Agent score
80%

What's inside flask-restplus

  1. Overview of Flask-RESTPlus

    master
    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.
  2. Handle Werkzeug HTTPExceptions

    master
    Werkzeug HTTPException objects are automatically serialized by Flask-RESTPlus using their description attribute. You can provide a custom message during instantiation or attach extra attributes to the exception object via the .data attribute to include them in the JSON output.
  3. Skip None values in responses

    master

    To reduce response size, you can skip fields that have a value of None instead of marshaling them as JSON null.

    Use the skip_none=True keyword argument in the @marshal_with decorator.

    Note: If you are using fields.Nested, you must also pass skip_none=True to the fields.Nested constructor to ensure nested fields are also skipped when they are None.

    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)
    })
  4. Configure OAuth2 Implicit Flow in Swagger UI

    master

    To enable OAuth2 Implicit Flow for interactive testing within the Swagger UI, configure the following Flask app configs and provide the authorizations dictionary to the Api constructor. Note that clientId is 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',
                }
            }
        }
    )
  5. Document API authorizations

    master

    You can document security requirements using the authorizations argument in the Api constructor. This argument accepts a Python dictionary representing Swagger securityDefinitions.

    To apply security to specific resources or methods, use the @api.doc(security='name') decorator. To apply security globally to all endpoints, use the security parameter in the Api constructor.

    To disable security for a specific method, pass None or an empty list [] to the security parameter 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):
            pass
  6. Run tests and quality checks with tox and inv qa

    master

    To ensure your code is compliant with flask-restplus standards before committing, you should run both the quality report and the tox test suite.

    tox runs the test suite against all supported Python versions and ensures documentation generates correctly. inv qa ensures code compliance with coding standards (PEP8 with a 120 character line length).

    You can run both simultaneously with a single command.

    $ inv qa tox
  7. Document errors in Swagger/OpenAPI

    master

    You can document errors in your API documentation using several methods:

    1. Decorator approach: Combine @api.errorhandler with @api.marshal_with and @api.header to define the response schema and headers.
    2. 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
  8. Maintain multiple API versions using Namespaces and Blueprints

    master
    To 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 own Api instance tied to a unique Blueprint. These versioned blueprints are then registered to the main Flask app.
  9. Use reqparse for request parsing

    master

    Flask-RESTPlus provides a reqparse module modeled after Python's argparse to provide uniform access to variables on the flask.request object.

    Note: This module is considered deprecated and slated for removal in version 2.0. It is recommended to consider integrating with packages like marshmallow for 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 (str in Python 3, unicode in 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()