Fully featured framework for fast, easy and documented API development with Flask

Overview

Flask RestPlus

Build status Code coverage Documentation status License Supported Python versions Join the chat at https://gitter.im/noirbizarre/flask-restplus

IMPORTANT NOTICE:

This project has been forked to Flask-RESTX and will be maintained by by the python-restx organization. Flask-RESTPlus should be considered unmaintained.

The community has decided to fork the project due to lack of response from the original author @noirbizarre. We have been discussing this eventuality for almost a year.

Things evolved a bit since that discussion and a few of us have been granted maintainers access to the github project, but only the original author has access rights on the PyPi project. As such, we been unable to make any actual releases. To prevent this project from dying out, we have forked it to continue development and to support our users.

Flask-RESTPlus is an extension for Flask that adds support for quickly building REST APIs. Flask-RESTPlus encourages best practices with minimal setup. If you are familiar with Flask, Flask-RESTPlus should be easy to pick up. It provides a coherent collection of decorators and tools to describe your API and expose its documentation properly using Swagger.

Compatibility

Flask-RestPlus requires Python 2.7 or 3.4+.

Installation

You can install Flask-Restplus with pip:

$ pip install flask-restplus

or with easy_install:

$ easy_install flask-restplus

Quick start

With Flask-Restplus, you only import the api instance to route and document your endpoints.

from flask import Flask
from flask_restplus import Api, Resource, fields

app = Flask(__name__)
api = Api(app, version='1.0', title='TodoMVC API',
    description='A simple TodoMVC API',
)

ns = api.namespace('todos', description='TODO operations')

todo = api.model('Todo', {
    'id': fields.Integer(readOnly=True, description='The task unique identifier'),
    'task': fields.String(required=True, description='The task details')
})


class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
        for todo in self.todos:
            if todo['id'] == id:
                return todo
        api.abort(404, "Todo {} doesn't exist".format(id))

    def create(self, data):
        todo = data
        todo['id'] = self.counter = self.counter + 1
        self.todos.append(todo)
        return todo

    def update(self, id, data):
        todo = self.get(id)
        todo.update(data)
        return todo

    def delete(self, id):
        todo = self.get(id)
        self.todos.remove(todo)


DAO = TodoDAO()
DAO.create({'task': 'Build an API'})
DAO.create({'task': '?????'})
DAO.create({'task': 'profit!'})


@ns.route('/')
class TodoList(Resource):
    '''Shows a list of all todos, and lets you POST to add new tasks'''
    @ns.doc('list_todos')
    @ns.marshal_list_with(todo)
    def get(self):
        '''List all tasks'''
        return DAO.todos

    @ns.doc('create_todo')
    @ns.expect(todo)
    @ns.marshal_with(todo, code=201)
    def post(self):
        '''Create a new task'''
        return DAO.create(api.payload), 201


@ns.route('/<int:id>')
@ns.response(404, 'Todo not found')
@ns.param('id', 'The task identifier')
class Todo(Resource):
    '''Show a single todo item and lets you delete them'''
    @ns.doc('get_todo')
    @ns.marshal_with(todo)
    def get(self, id):
        '''Fetch a given resource'''
        return DAO.get(id)

    @ns.doc('delete_todo')
    @ns.response(204, 'Todo deleted')
    def delete(self, id):
        '''Delete a task given its identifier'''
        DAO.delete(id)
        return '', 204

    @ns.expect(todo)
    @ns.marshal_with(todo)
    def put(self, id):
        '''Update a task given its identifier'''
        return DAO.update(id, api.payload)


if __name__ == '__main__':
    app.run(debug=True)

Contributors

Flask-RESTPlus is brought to you by @noirbizarre. Since early 2019 @SteadBytes, @a-luna, @j5awry, @ziirish volunteered to help @noirbizarre keep the project up and running. Of course everyone is welcome to contribute and we will be happy to review your PR's or answer to your issues.

Documentation

The documentation is hosted on Read the Docs

Contribution

Want to contribute! That's awesome! Check out CONTRIBUTING.rst!

Issues
  • App runs locally but returns 500 error on Heroku

    App runs locally but returns 500 error on Heroku

    There doesn't seem to be any documentation on deploying to Heroku with flask-restplus. I've just deployed an app and am getting the following: Error: INTERNAL SERVER ERROR.

    My Procfile is set to web: gunicorn app:app and my app is set as api = Api(app), app.wsgi_app = ProxyFix(app.wsgi_app), and app = Flask(__name__), respectively. Anyone have any suggestions?

    opened by rah-ool 33
  • AttributeError: Api does not have __schema__ attribute

    AttributeError: Api does not have __schema__ attribute

    Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information.

    Flask (0.11.1) flask-restplus (0.9.2) Flask-Script (2.0.5)

    [2016-08-17 15:07:57,503] ERROR in app: Exception on /mailang/api/v1/swagger.json [GET] Traceback (most recent call last): File "E:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request rv = self.dispatch_request() File "E:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request return self.view_functionsrule.endpoint File "E:\Python27\lib\site-packages\flask_restplus\api.py", line 310, in wrapper resp = resource(_args, *_kwargs) File "E:\Python27\lib\site-packages\flask\views.py", line 84, in view return self.dispatch_request(_args, *_kwargs) File "E:\Python27\lib\site-packages\flask_restplus\resource.py", line 44, in dispatch_request resp = meth(_args, *_kwargs) File "E:\Python27\lib\site-packages\flask_restplus\api.py", line 751, in get return self.api.schema File "E:\Python27\lib\site-packages\flask_restplus\api.py", line 206, in getattr raise AttributeError('Api does not have {0} attribute'.format(name)) AttributeError: Api does not have schema attribute 127.0.0.1 - - [17/Aug/2016 15:07:57] "GET /mailang/api/v1/swagger.json HTTP/1.1" 500 -

    Need more feedback 
    opened by 984958198 25
  • Refactor for accepting Marshmallow and other marshaling libraries

    Refactor for accepting Marshmallow and other marshaling libraries

    This is less of an issue and more of an intent to implement :shipit:

    Result

    The result of this work should be these two main things:

    • It should be possible to build alternative request parsing implementations.
    • It should be possible to use Marshmallow as easily as the current request parsing implementation.

    I intend to try doing this without losing backward compatibility of public APIs, so that most applications can update without having to rewrite their marshaling implementations. No promises of course about the internal API.

    Planning

    My plan of attack is as follows (may later be filled out with "subtasks"):

    • [ ] Design initial additions/changes to the public API through a simple "sample app"

      I'm simultaneously building a real world product with RestPlus and Marshmallow (hacked in) for my employer @l1ndanl. This should help a ton, since I can my experiences and "wish list" from that to design the public API.

      This implementation might be useful later for testing the implementation, but it shouldn't be set in stone. Implementation details may have to change the actual public API.

    • [ ] Locate and split out all touch points of the internal APIs with request parsing

      Before I design the abstraction layer I'd like to make sure I know exactly what the internal API needs to be able to do and where it's used. This will require some more extensive knowledge of RestPlus internals and since these uses will have to be split out anyway eventually, doing this before designing the abstraction should make it a lot easier for me.

    • [ ] Design the abstraction layer

    • [ ] Implement the abstraction layer for the "legacy" request parsing

    • [ ] Implement an abstraction layer for Marshmallow and/or webargs

    Methodology

    I'll obviously be developing in my own fork of RestPlus in a special branch, that can then eventually be merged through a PR.

    I'm also very interested in suggestions/ideas/insider info/similar projects + shows of support 🎉 .

    Related reading...

    • https://github.com/noirbizarre/flask-restplus/issues/410
    • https://github.com/noirbizarre/flask-restplus/issues/317
    • https://github.com/noirbizarre/flask-restplus/issues/9
    • The warning on this page: http://flask-restplus.readthedocs.io/en/stable/parsing.html
    opened by martijnarts 24
  • Support vendor fields

    Support vendor fields

    Swagger allow to add custom/vendor fields at every level: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#vendorExtensions

    flask-restplus should support declaring vendor fields.

    @Kelvinm you said in #44 that you have some local modification on the subject. Do you mind to share them ?

    enhancement 
    opened by noirbizarre 22
  • Fix ambiguity error with Polymorphism candidates (isinstance() problem)

    Fix ambiguity error with Polymorphism candidates (isinstance() problem)

    Right now Polymorphism fails when using something like this (models in sqlalchemy):

    models:

    class Product(BaseModel):
    	discr = Column(String)
    
    	__mapper_args__ = {
    		'polymorphic_on': discr,
            'polymorphic_identity': "product"
    	}
    
    class VegetableProduct(Product):
    	name = Column(String)
    
        __mapper_args__ = {
    		'polymorphic_identity': "vegetable"
    	}
    
    class DairyProduct(VegetableProduct):
        __mapper_args__ = {
    		'polymorphic_identity': "dairy"
    	}
    

    mapper:

    resource_product = api.model("Product", {
    	'discr': fields.String
    })
    
    product_mapper = {
    	VegetableProduct: api.inherit("Vegetable", resource_product, { 'name': fields.String }),
    	DairyProduct: api.inherit("Dairy", resource_product, { 'name': fields.String }),
    }
    
    resource_result = api.model("ResourceResult", {
    	'products': fields.List(fields.Polymorphism(product_mapper))
    })
    

    This sparkles error here:

    https://github.com/noirbizarre/flask-restplus/blob/master/flask_restplus/fields.py#L682

    Because candidates will be: VegetableProduct and DairyProduct, since isinstance() will return True for both classes (I personally surprised it works like this)

    But actually it should be only DairyProduct

    Checking by __class__.__name__ removes this error and it works as intended.

    I hope my quick fix did not break anything, I'm eager to update it if I don't know, more elegant solution is needed.

    opened by idchlife 18
  • Splitting up API library into multiple files

    Splitting up API library into multiple files

    I've tried several different ways to split up the API files into separate python source but have come up empty. I love the additions to flask-restplus but it appears that only the classes within the main python file are seen. Is there a good example of how to do this? In Flask-Restful it was a bit simpler as you could just add the resource and point to a different python file that got imported.

    help wanted 
    opened by kinabalu 16
  • Defining varaible keys in case of nested field model

    Defining varaible keys in case of nested field model

    	"preview": {
    		"9:16": {
    			"thumbnail": "",
    			"video": ""
    		}, "16:9": {
    			"thumbnail": "",
    			"video": ""
    		}, "1:1": {
    			"thumbnail": "",
    			"video": ""
    		}
    	}
    

    I have the above data coming in the request for which I want to create a model. I tried implementing wildcard fields but didn't get any success. In the above case, the aspect ratio is dynamic and can be anything but will always be in *:* format. In case that is coming, thumbnail and video are in nested modal with required= true.

    Any leads would be appreciated. Thanks in advance!

    enhancement in progress 
    opened by knowBalpreet 15
  • Set 'errors' attribute via kwarg in Api.init_app

    Set 'errors' attribute via kwarg in Api.init_app

    required to support flask-restful extended error handling

    opened by robertglen 14
  • [proposal] better support for security requirements

    [proposal] better support for security requirements

    What I'm proposing, and willing to implement and contribute is a SecurityRequirement class, possibly with subclasses like OAuth2SecurityRequirement. defining an api with these requirements would look like this:

    oauth2_req = OAuth2SecurityRequirement(name="needsuser", scopes=["scope1", "scope2"], flow="implicit", authorization_uri="http://example.com/authorize")
    apikey_req = ApiKeyRequirement(name="apikey", param_name="key", in="query")
    
    to require either one of these api requirements api-wide, you'd pass an array of instances to the API constructor.
    
    
    ```python
    Api(title="my apy", version="v1", security_requirements=[
        apikey_req,
        oauth2_req("scope1")
    ])
    

    Note that oauth2 requirement instances are callable, so you can pass in required scopes.

    I'd be very much willing to implementthis and contribute the code back to this project if you're interested.

    enhancement 
    opened by bigblind 14
  • Documenting using json schema

    Documenting using json schema

    First pass at adding a SchemaModel for documenting using json schema

    opened by stevezau 14
  • Documentation suggestions

    Documentation suggestions

    As I was reading part of the documentation, I found a missing apostrophe in the documentation of the Api class.

    In addition, I'm suggesting adding a jump link in the contributing document and smoothing out a sentence.

    opened by Chris-May 0
  • Update api.py

    Update api.py

    null

    opened by ghost 0
  • Fixed incorrect werkzeug import

    Fixed incorrect werkzeug import

    null

    opened by 0x78f1935 0
  • How to use swagger with a old flask project.

    How to use swagger with a old flask project.

    I have system that is build with two API one is mine and another is third-part maintaned. How can I add swagger without modify the source of the third-part software.

    I build a POC in the source below: PoC

    simple_page.py

    # Pure flask page
    from flask import Blueprint, render_template, abort
    from jinja2 import TemplateNotFound
    
    simple_page = Blueprint('simple_page', __name__,
                            template_folder='templates')
    
    @simple_page.route('/', defaults={'page': 'index'})
    @simple_page.route('/<page>')
    def show(page):
        try:
            return render_template('%s.html' % page)
        except TemplateNotFound:
            abort(418)
    

    other_page.py

    #restplus based artecture
    from flask import Blueprint, render_template, abort, Flask
    from jinja2 import TemplateNotFound
    app = Flask(__name__)
    
    other_page = Blueprint('other_page', __name__)
    
    from flask_restplus import Api, Resource, fields
    
    api = Api(other_page, version='1.0', title='Todo API',
        description='A simple TODO API', doc='/doc/', template_folder='templates',
    )
    
    
    @api.route('/')
    class TodoSimple(Resource):
        def get(self):
            try:
                return render_template('other_page.html')
            except TemplateNotFound:
                abort(418)
    

    simple.py

    from flask import Flask
    from simple_page import simple_page
    from other_page import other_page
    from flask_restplus import Api
    
    app = Flask(__name__)
    api = Api(simple_page, doc='/doc/')
    
    
    app.register_blueprint(simple_page)
    #app.register_blueprint(simple_page, url_prefix='/simple_page')
    app.register_blueprint(other_page, url_prefix='/other_page')
    app.run()
    

    with this I get the doc page but a message "No operations defined in spec!". Screen Shot 2021-07-02 at 6 35 50 PM

    And the rest_plus page I get the documentation normal.

    opened by engFelipeMonteiro 0
  • Provide doc that api.expect doesn't support multipart form data

    Provide doc that api.expect doesn't support multipart form data

    Flask restplus event wont give to you info that this is not supported it just breaks apart.

    bug 
    opened by Randomneo 1
  • Add support for OpenAPI (Swagger 3.0)

    Add support for OpenAPI (Swagger 3.0)

    It would be very nice to have OpenAPI (Swagger 3.0) update. I would need it.

    bug 
    opened by mindej 1
  • Values in nested  api model are null

    Values in nested api model are null

    Hello, I hope you can help me. Im using python 3.9.0, Flask 1.1.2, flask-restplus 0.13.0, Flask_SQLAlchemy2.4.4 and SQLAlchemy 1.3.20.

    I have a problem with a nested api model, which looks like this:

    lightstate = api.model('LightState', {
        'red': fields.Integer(attribute='red', description='red part of the rgb light'),
        'green': fields.Integer(attribute='green', description='green part of the rgb light'),
        'blue': fields.Integer(attribute='blue', description='blue part of the rgb light'),
        'bri': fields.Integer(attribute='bri', description='brightness of the light')    
    })
    lights = api.model('Lights',{
        'id': fields.Integer(readOnly=True, description='The database id of the light'),
        'name': fields.String(required=True, description='light name'),
        'state': fields.Nested(lightstate)
    })
    

    This is my my request handler:

    namespace = api.namespace('light'')
    
    @namespace.route('/')
    class Light(Resource):
        @api.marshal_with(lights)
        def get(self):
            light_data = Lights.query.all()
            return light_data
    

    And my dto:

    db = SQLAlchemy()
    
    class Lights(db.Model):
        __bind_key__ = 'lights'
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(255))
        red = db.Column(db.Integer)
        green = db.Column(db.Integer)
        blue = db.Column(db.Integer)
        bri = db.Column(db.Integer)
    
        def __init__(self, name, red, green, blue, bri):
            self.name = name
            self.red = red
            self.green = green
            self.blue = blue
            self.bri = bri
    

    If I send a request, I'm getting this response with null values:

    [
      {
        "id": 1,
        "name": "garden",
        "state": {
          "red": null,
          "green": null,
          "blue": null,
          "bri": null
        }
      },
      {
        "id": 2,
        "name": "pool",
        "state": {
          "red": null,
          "green": null,
          "blue": null,
          "bri": null
        }
      }
    ]
    

    But if I remove the nested field from my api model 'lights' and add all fields, the values are not null.

    lights = api.model('Lights', {
        'id': fields.Integer(readOnly=True, description='The database id of the light'),
        'name': fields.String(required=True, description='light name'),
        'red': fields.Integer(description='red part of the rgb light'),
        'green': fields.Integer(description='green part of the rgb light'),
        'blue': fields.Integer(description='blue part of the rgb light'),
        'bri': fields.Integer(description='brightness of the light')
    })
    
    [
      {
        "id": 1,
        "name": "garden",
        "red": 50,
        "green": 205,
        "blue": 50,
        "bri": 84
      },
      {
        "id": 2,
        "name": "pool",
        "red": 255,
        "green": 42,
        "blue": 255,
        "bri": 96
      }
    ]
    

    I want to use the nested fields. How do I get the values in my response?

    Thanks in advance

    opened by aklehm 2
  • With nested api model expect is raising error with key not found.

    With nested api model expect is raising error with key not found.

    We have flask_restplus for our API, in one of the post requests we have a nested structure. When we validate input json with expect decorator it is raising the key error. API model is

    user_expected_field = api.model('UserRequest', {
                "user_email": fields.String(example='[email protected]', required=True),
                "user_name": fields.String(example="user", required=True),
                "user_gender": fields.String(example="Male", required=True),
                "user_address":fields.List(fields.Nested(api.model(
                           "AddressModel", {
                                    "street1": field.String(required=True),
                                    "street2": field.String(required=True),
                                    "city": field.String(required=True),
                                    "state": field.String(required=True),
                                    "country": field.String(required=True),
                            }
                )))
            },
        )
    

    Error:

    Traceback (most recent call last): File "/lib/python3.6/site-packages/jsonschema/validators.py", line 812, in resolve_fragment document = document[part] KeyError: 'AddressModel'

    Any help will be highly appreciated.

    opened by BHAUTIK04 0
  • DDtrace auto instrumentation does not work for flaskrestplus apis PATCH, POST

    DDtrace auto instrumentation does not work for flaskrestplus apis PATCH, POST

    Does DDtrace work automatically with flask restplus resources ? Our Get resource is getting traced but not Post, Patch .

    Environment

    ddtrace==0.33.0 Flask==1.0.4 flask-restplus==0.13.0 python==3.6.8

    bug 
    opened by kasturichavan 0
  • Scheme to replace swagger.json

    Scheme to replace swagger.json

    I want to change the json address of swagger from http://127.0.0.1:8080/swagger.json to http://127.0.0.1:8080/v2/api-docs, whether it supports such operations or has related parameter configuration

    bug 
    opened by somta 2
Goblet is an easy-to-use framework that enables developers to quickly spin up fully featured REST APIs with python on GCP

GOBLET Goblet is a framework for writing serverless rest apis in python in google cloud. It allows you to quickly create and deploy python apis backed

Austen 31 Nov 23, 2021
Chisel is a light-weight Python WSGI application framework built for creating well-documented, schema-validated JSON web APIs

chisel Chisel is a light-weight Python WSGI application framework built for creating well-documented, schema-validated JSON web APIs. Here are its fea

Craig Hobbs 2 Oct 1, 2021
Daniel Vaz Gaspar 3.6k Nov 23, 2021
Flask-Potion is a RESTful API framework for Flask and SQLAlchemy, Peewee or MongoEngine

Flask-Potion Description Flask-Potion is a powerful Flask extension for building RESTful JSON APIs. Potion features include validation, model resource

DTU Biosustain 482 Nov 23, 2021
Flask-Potion is a RESTful API framework for Flask and SQLAlchemy, Peewee or MongoEngine

Flask-Potion Description Flask-Potion is a powerful Flask extension for building RESTful JSON APIs. Potion features include validation, model resource

DTU Biosustain 484 Feb 3, 2021
Pyrin is an application framework built on top of Flask micro-framework to make life easier for developers who want to develop an enterprise application using Flask

Pyrin A rich, fast, performant and easy to use application framework to build apps using Flask on top of it. Pyrin is an application framework built o

Mohamad Nobakht 7 Nov 15, 2021
Appier is an object-oriented Python web framework built for super fast app development.

Joyful Python Web App development Appier is an object-oriented Python web framework built for super fast app development. It's as lightweight as possi

Hive Solutions 119 Nov 25, 2021
Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints.

Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints. check parameters and generate API documents automatically. Flask Sugar是一个基于flask,pyddantic,类型注解的API框架, 可以检查参数并自动生成API文档

null 60 Nov 29, 2021
FastAPI framework, high performance, easy to learn, fast to code, ready for production

FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https:

Sebastián Ramírez 38.6k Nov 23, 2021
Free and open source full-stack enterprise framework for agile development of secure database-driven web-based applications, written and programmable in Python.

Readme web2py is a free open source full-stack framework for rapid development of fast, scalable, secure and portable database-driven web-based applic

null 2k Nov 22, 2021
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 15.6k Dec 1, 2021
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 15.6k Nov 22, 2021
APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects

APIFlask APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects. It's easy to use, highly customizable, ORM/O

Grey Li 350 Nov 27, 2021
A public API written in Python using the Flask web framework to determine the direction of a road sign using AI

python-public-API This repository is a public API for solving the problem of the final of the AIIJC competition. The task is to create an AI for the c

Lev 1 Nov 8, 2021
A minimal, extensible, fast and productive API framework for Python 3.

molten A minimal, extensible, fast and productive API framework for Python 3. Changelog: https://moltenframework.com/changelog.html Community: https:/

Bogdan Popa 971 Nov 27, 2021
A boilerplate Flask API for a Fullstack Project with some additional packages and configuration prebuilt. ⚙

Flask Boilerplate to quickly get started with production grade flask application with some additional packages and configuration prebuilt.

Yasser Tahiri 31 Nov 28, 2021
Swagger/OpenAPI First framework for Python on top of Flask with automatic endpoint validation & OAuth2 support

Connexion Connexion is a framework that automagically handles HTTP requests based on OpenAPI Specification (formerly known as Swagger Spec) of your AP

Zalando SE 3.9k Dec 1, 2021
Swagger/OpenAPI First framework for Python on top of Flask with automatic endpoint validation & OAuth2 support

Connexion Connexion is a framework that automagically handles HTTP requests based on OpenAPI Specification (formerly known as Swagger Spec) of your AP

Zalando SE 3.5k Feb 17, 2021
Otter is framework for creating microservices in Flask like fassion using RPC communication via message queue.

Otter Framework for microservices. Overview Otter is framework for creating microservices in Flask like fassion using RPC communication via message qu

Volodymyr Biloshytskyi 3 Oct 13, 2021