Browsable web APIs for Flask.

Related tags

RESTful APIflask-api
Overview

Flask API

Browsable web APIs for Flask.

Unix Build Status Coverage Status Scrutinizer Code Quality PyPI Version

Status: This project is in maintenance mode. The original author (Tom Christie) has shifted his focus to API Star. Passing PRs will still be considered for releases by the maintainer (Jace Browning).

Overview

Flask API is a drop-in replacement for Flask that provides an implementation of browsable APIs similar to what Django REST framework offers. It gives you properly content-negotiated responses and smart request parsing:

Screenshot

Installation

Requirements:

  • Python 3.6+
  • Flask 1.1.+

Install using pip:

$ pip install Flask-API

Import and initialize your application:

from flask_api import FlaskAPI

app = FlaskAPI(__name__)

Responses

Return any valid response object as normal, or return a list or dict.

@app.route('/example/')
def example():
    return {'hello': 'world'}

A renderer for the response data will be selected using content negotiation based on the client 'Accept' header. If you're making the API request from a regular client, this will default to a JSON response. If you're viewing the API in a browser, it'll default to the browsable API HTML.

Requests

Access the parsed request data using request.data. This will handle JSON or form data by default.

@app.route('/example/')
def example():
    return {'request data': request.data}

Example

The following example demonstrates a simple API for creating, listing, updating and deleting notes.

from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions

app = FlaskAPI(__name__)


notes = {
    0: 'do the shopping',
    1: 'build the codez',
    2: 'paint the door',
}

def note_repr(key):
    return {
        'url': request.host_url.rstrip('/') + url_for('notes_detail', key=key),
        'text': notes[key]
    }


@app.route("/", methods=['GET', 'POST'])
def notes_list():
    """
    List or create notes.
    """
    if request.method == 'POST':
        note = str(request.data.get('text', ''))
        idx = max(notes.keys()) + 1
        notes[idx] = note
        return note_repr(idx), status.HTTP_201_CREATED

    # request.method == 'GET'
    return [note_repr(idx) for idx in sorted(notes.keys())]


@app.route("/<int:key>/", methods=['GET', 'PUT', 'DELETE'])
def notes_detail(key):
    """
    Retrieve, update or delete note instances.
    """
    if request.method == 'PUT':
        note = str(request.data.get('text', ''))
        notes[key] = note
        return note_repr(key)

    elif request.method == 'DELETE':
        notes.pop(key, None)
        return '', status.HTTP_204_NO_CONTENT

    # request.method == 'GET'
    if key not in notes:
        raise exceptions.NotFound()
    return note_repr(key)


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

Now run the webapp:

$ python ./example.py
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader

You can now open a new tab and interact with the API from the command line:

$ curl -X GET http://127.0.0.1:5000/
[{"url": "http://127.0.0.1:5000/0/", "text": "do the shopping"},
 {"url": "http://127.0.0.1:5000/1/", "text": "build the codez"},
 {"url": "http://127.0.0.1:5000/2/", "text": "paint the door"}]

$ curl -X GET http://127.0.0.1:5000/1/
{"url": "http://127.0.0.1:5000/1/", "text": "build the codez"}

$ curl -X PUT http://127.0.0.1:5000/1/ -d text="flask api is teh awesomez"
{"url": "http://127.0.0.1:5000/1/", "text": "flask api is teh awesomez"}

You can also work on the API directly in your browser, by opening http://127.0.0.1:5000/. You can then navigate between notes, and make GET, PUT, POST and DELETE API requests.

Issues
  • Towards 1.0

    Towards 1.0

    I've been doing some preliminary work on a new Flask API framework. Given that I've never maintained Flask-API, and it's only ever been a very weak port of a few bits of REST framework, I'm strongly considering using this project for the latest work, and releasing it as a 1.0 version.

    I'm really pleased with the incoming work, which is super simple, but features automatic client libraries & command line tool, plus schema generation in a nice & agnostic way (so, eg provide Swagger, API Blueprint, or any other schema type documentation out of the box)

    I figure it's worth raising the issue here to see how folks would feel about an incompatible 1.0 release, if it was something that was actually going to push things forwards and be a release that I was actually using and significantly invested in for a change.

    Any thoughts?

    question 
    opened by tomchristie 14
  • New maintainer?

    New maintainer?

    @tomchristie has mentioned in #31 and #32 that he is not currently maintaining this project. I'm interested in helping support a 0.6.x release with bug fixes. Can we talk about which of these options is best to move forward on this repo:

    1. contributors create pull requests and @tomchristie merges
    2. add additional collaborators with push permission
    3. transfer ownership of this repo to someone else
    4. create a GitHub organization for this repo and add collaborators to that
    opened by jacebrowning 11
  • Release v0.6.3

    Release v0.6.3

    Also cleaned up some spelling/formatting issues for release.

    opened by jacebrowning 10
  • AttributeError: 'tuple' object has no attribute 'items'

    AttributeError: 'tuple' object has no attribute 'items'

    Related to #58, I am now hitting a spot where blueprint_handlers and app_handlers are both empty tuples with Flask 0.11 and 0.11.1, so the fix in #59 actually causes a new issue:

    Traceback (most recent call last):
      File ".../env/lib/python3.5/site-packages/flask/app.py", line 2000, in __call__
        return self.wsgi_app(environ, start_response)
      File ".../env/lib/python3.5/site-packages/flask/app.py", line 1991, in wsgi_app
        response = self.make_response(self.handle_exception(e))
      File ".../env/lib/python3.5/site-packages/flask/app.py", line 1567, in handle_exception
        reraise(exc_type, exc_value, tb)
      File ".../env/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
        raise value
      File ".../env/lib/python3.5/site-packages/flask/app.py", line 1988, in wsgi_app
        response = self.full_dispatch_request()
      File ".../env/lib/python3.5/site-packages/flask/app.py", line 1641, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File ".../env/lib/python3.5/site-packages/flask_api/app.py", line 97, in handle_user_exception
        for typecheck, handler in chain(blueprint_handlers.items(), app_handlers.items()):
    AttributeError: 'tuple' object has no attribute 'items'
    
    help wanted 
    opened by jacebrowning 9
  • Using with a Blueprint

    Using with a Blueprint

    Does Flask-API supports blueprint? The example is only using the Flask initialization.

    opened by rabc 9
  • No content responses should accept not only an empty string

    No content responses should accept not only an empty string

    Is confusing, specially when trying to keep consistence beetwen returned data types, that to be able to send a 204 HTTP status code is needed to pass only an empty string not being valid and empty dictionary or None value for example.

    Could be more flexible to support other "empty/no content" values.

    help wanted 
    opened by jesugmz 7
  • Support for non-English string

    Support for non-English string

    I rewrite the notes in example.py

    notes = {
        0: '购物',
        1: 'build the codez',
        2: 'paint the door',
    }
    

    I get an exception: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 16: ordinal not in range

    opened by jacktan1991 7
  • Allow custom template when inheriting BrowsableAPIRenderer

    Allow custom template when inheriting BrowsableAPIRenderer

    It would be useful to be able to inherit BrowsableAPIRenderer and set a different jinja template.

    opened by jaidhyani 7
  • v0.7.0 release breaks expected behavior

    v0.7.0 release breaks expected behavior

    One of the chief reasons we use FlaskAPI at Qualcomm is because of how easy it makes returning JSON content from a simple function. However, it seems something between v0.6.9 and v0.7.0 broke this behavior; if you try to return data that isn't a dict or list from a Flask handler, you get a text/html response back, whereas you used to get an application/json response back.

    In v0.6.9:

    [[email protected]]$ curl --include --insecure https://10.52.252.96:3519/api/v1/mapping/test_mapping/key1
    HTTP/1.0 200 OK
    Content-Type: application/json
    Content-Length: 8
    Access-Control-Allow-Origin: *
    Server: Werkzeug/0.12.1 Python/3.5.3
    Date: Tue, 11 Apr 2017 03:40:13 GMT
    Connection: keep-alive
    
    "value1"
    

    In v0.7.0:

    [[email protected]]$ curl --include --insecure https://10.52.252.96:3519/api/v1/mapping/test_mapping/key1
    HTTP/1.0 200 OK
    Content-Type: text/html; charset=utf-8
    Content-Length: 6
    Access-Control-Allow-Origin: *
    Server: Werkzeug/0.12.1 Python/3.5.3
    Date: Tue, 11 Apr 2017 03:45:21 GMT
    Connection: keep-alive
    
    value1
    

    It's OK if the new behavior is intentional -- if so, just please provide a way to get the old behavior back, because we are depending on it.

    opened by skaven81 6
  • Project abandoned?

    Project abandoned?

    It seems that latest updated are getting and older. Same for other branches. Is the project fully abandoned with no v1.0 as planed?

    question 
    opened by vinyll 6
  • How could Flask 2.x's MethodView be used with this?

    How could Flask 2.x's MethodView be used with this?

    Since Flask 2.x there has been a MethodView class that allows users to define api method-based classes for entity management. Can an example be provided showing how to use these new class-centric routes with flask-api?

    Example MethodView:

    from flask import current_app as app
    from flask.views import MethodView
    
    class ExampleEndpoint(MethodView):
        """ Example of a class inheriting from flask.views.MethodView 
    
        All 5 request methods are available at /api/example/<entity>
        """
        def get(self, entity):
            """ Responds to GET requests """
            return "Responding to a GET request"
    
        def post(self, entity):
            """ Responds to POST requests """
            return "Responding to a POST request"
    
        def put(self, entity):
            """ Responds to PUT requests """
            return "Responding to a PUT request"
    
        def patch(self, entity):
            """ Responds to PATCH requests """
            return "Responding to a PATCH request"
    
        def delete(self, entity):
            """ Responds to DELETE requests """
            return "Responding to a DELETE request"
    
    app.add_url_rule("/api/example/<entity>", view_func=ExampleEndpoint.as_view("example_api"))
    
    
    opened by caffeinatedMike 0
  • Using it with flask-restful breaks rendering

    Using it with flask-restful breaks rendering

    Hi,

    I've tried the module using traditional route definition and it works perfectly.

    But when using flask-restful to build my API, the rendering is broken and I can't longer get the browsable API. I then just have a poor text (http response) on a blank page.

    I think that's because I use classes instead of functions for my routes, with HTTP methods directly defined as route's class methods, and therefore flask-api behaves an unexpectable way for rendering.

    Has someone here tried that please?

    Regards, Eugène NG

    opened by papiveron 2
  • PUT on the browsable API renderer actually performs POST

    PUT on the browsable API renderer actually performs POST

    Given a route that accepts PUT and GET but not POST, the browsable API renderer performs a POST despite the button very clearly showing PUT.

    image image

    from flask_api import FlaskAPI
    
    app = FlaskAPI(__name__)
    
    @app.route("/", methods=["PUT", "GET"])
    def index():
        return {}
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    requirements.txt

    bug help wanted 
    opened by andreareina 5
  • Use with a REST-API.

    Use with a REST-API.

    Quick question: Can I use this with a REST API? Specifically: My Own.

    opened by TechStudent11 0
  • Flask API XML output?

    Flask API XML output?

    Hello, sorry if this would not be the place to ask for help..

    But could I use Flask API for XML output?

    Any chance for how I could modify the Flask Code to Flask API?

    from flask import Flask, Response
    
    
    class MyResponse(Response):
        default_mimetype = 'application/xml'
    
    class MyFlask(Flask):
        response_class = MyResponse
    
        
    app = MyFlask(__name__)
    
    
    @app.route('/')
    def get_data():
        return '''<?xml version="1.0" encoding="UTF-8"?>
    <person>
        <name>John Smith</name>
    </person>
    '''
    
    if __name__ == '__main__':
        app.run(debug=True)
    
    
    question 
    opened by bbartling 0
  • Content negotiation ignores quality

    Content negotiation ignores quality

    The quality (q) parameter in the Accept header has no influence on the selected renderer.

    When negotiating the Content-Type of a response, each candidate is currently awarded a "precedence" based on how complete the media type is. (Fully specified types with parameters are highest, wildcards are lowest.) Even if I supply two media types with the same precedence in the Accept header, the selected type is subject to the order they are encountered while iterating the set of types of the same precedence.

    I would propose this be improved to support quality using the same rules as Apache: https://httpd.apache.org/docs/current/content-negotiation.html

    • Use quality specifier from the request if provided
    • Fully specified types are implicitly q=1.0
    • Partially specified types (text/*) are implicitly q=0.02
    • Unspecified types (*/*) are implicily q=0.01

    I am about to implement this as a custom negotiator class but will happily supply a PR if the work is warranted.

    opened by james-emerton 0
  • modified json.dumps parameters in renderers.py and set Access-Control…

    modified json.dumps parameters in renderers.py and set Access-Control…

    While calling json.dumps in renderers.py, I have changed 'ensure_ascii' to True and started passing 'default' parameter with value str. Apart from this I have set Access-Control-Allow-Origin to * in response.py, which is generally required in APIs.

    opened by aloknayak29 0
  • Accept: 'application/json; indent=4' not working.

    Accept: 'application/json; indent=4' not working.

    Hi, The header mentioned in question title is raising:
    Exception:flask_api.exceptions.NotAcceptable: Could not satisfy the request Accept header I am trying the demo app using Postman to test request. Any ideas why is this not loading JSONRenderer() object?

    EDIT: What i understand from further debugging is that select_renderer() from Class DefaultNegotiation tries to match application/json and application/json;indent=4 through satisfies() from Class Media. But server_media_type is initialized to JSONRenderer media_type attribute. I added following check to the satisfies() and it works:

    if self.full_type == other.full_type:
                return True
    

    Is this correct? Or there is some other way of doing it without modifying the code?

    help wanted 
    opened by sohaibfarooqi 1
  • No way to customize ``view_name`` in html templace

    No way to customize ``view_name`` in html templace

    Currently it's generated by simple

    def convert_to_title(name):
        return name.replace('-', ' ').replace('_', ' ').replace('.', ' ').capitalize()
    

    but for example if endpoint contains . it becomes strange

    help wanted 
    opened by bubenkoff 1
  • BrowsableAPIRenderer.render assumes url_rule is not None

    BrowsableAPIRenderer.render assumes url_rule is not None

    I've encountered this exception:

    Traceback (most recent call last):
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask\app.py", line 1836, in __call__
        return self.wsgi_app(environ, start_response)
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask\app.py", line 1820, in wsgi_app
        response = self.make_response(self.handle_exception(e))
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask\app.py", line 1403, in handle_exception
        reraise(exc_type, exc_value, tb)
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask\_compat.py", line 33, in reraise
        raise value
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask\app.py", line 1817, in wsgi_app
        response = self.full_dispatch_request()
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask\app.py", line 1478, in full_dispatch_request
        response = self.make_response(rv)
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask_api\app.py", line 58, in make_response
        rv = self.response_class(rv, headers=headers, status=status_or_headers)
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask_api\response.py", line 17, in __init__
        content = renderer.render(content, media_type, **options)
      File "C:\Users\100496078\Source\panda-insights\panda_api\env\lib\site-packages\flask_api\renderers.py", line 104, in render
        endpoint = request.url_rule.endpoint
    AttributeError: 'NoneType' object has no attribute 'endpoint'
    

    This is due to the line:

    endpoint = request.url_rule.endpoint
    

    As documented in Flask's API docs, url_rule may be None in some situations (e.g. for a 404 handler).

    Here's a simple piece of demo code to show the bug in action:

    from flask.ext.api import FlaskAPI
    
    app = FlaskAPI(__name__)
    
    @app.errorhandler(404)
    def not_found(error):
        return {}
    
    app.run(debug=True)
    
    bug help wanted 
    opened by Patman64 5
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 812 Jan 31, 2022
Integrate GraphQL into your Django project.

Graphene-Django A Django integration for Graphene. 💬 Join the community on Slack Documentation Visit the documentation to get started! Quickstart For

GraphQL Python 3.8k Jan 28, 2022
DRF-extensions is a collection of custom extensions for Django REST Framework

Django REST Framework extensions DRF-extensions is a collection of custom extensions for Django REST Framework Full documentation for project is avail

Gennady Chibisov 1.3k Jan 26, 2022
REST API with Flask. No data persistence.

Flask REST API Python 3.9.7 The Flask experience, without data persistence :D First, to install all dependencies: python -m pip install -r requirement

Luis Quiñones Requelme 1 Dec 14, 2021
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 2.6k Jan 29, 2022
The no-nonsense, minimalist REST and app backend framework for Python developers, with a focus on reliability, correctness, and performance at scale.

The Falcon Web Framework Falcon is a reliable, high-performance Python web framework for building large-scale app backends and microservices. It encou

Falconry 8.7k Jan 27, 2022
Estudo e desenvolvimento de uma API REST

Estudo e desenvolvimento de uma API REST 🧑‍💻 Tecnologias Esse projeto utilizará as seguintes tecnologias: Git Python Flask DBeaver Vscode SQLite 🎯

Deusimar 4 Aug 15, 2021
Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

django-cors-headers A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django a

Adam Johnson 4.5k Jan 24, 2022
Country-specific Django helpers, to use in Django Rest Framework

django-rest-localflavor Country-specific serializers fields, to Django Rest Framework Documentation (soon) The full documentation is at https://django

Gilson Filho 17 Jul 21, 2021
Dropdown population implementation for Django REST Framework

drf-dropdown Dropdown population implementation for Django REST Framework Usage Add DropdownView to API URL # urls.py import dropdown urlpatterns = [

Preeti Yuankrathok 2 Jan 20, 2022
Automatically generate a RESTful API service for your legacy database. No code required!

sandman2 sandman2 documentation [ ~ Dependencies scanned by PyUp.io ~ ] sandman2 automagically generates a RESTful API service from your existing data

Jeff Knupp 1.8k Jan 28, 2022
RESTful Todolist API

RESTful Todolist API GET todolist/ POST todolist/ {"desc" : "Description of task to do"} DELETE todolist/int:id PUT todolist/int:id Requirements D

Gabriel Tavares 5 Dec 19, 2021
Simplified REST API to get stickers from Snap

Snap Sticker kit REST API Simplified REST API to get stickers from Snap 💻 Instructions Search stickers Request: url = "https://sticker-kit-horizon733

Dishant Gandhi 1 Jan 04, 2022
Django queries

Djaq Djaq - pronounced “Jack” - provides an instant remote API to your Django models data with a powerful query language. No server-side code beyond t

Paul Wolf 40 Jan 16, 2022
DSpace REST API Client Library

DSpace Python REST Client Library This client library allows Python 3 scripts (Python 2 probably compatible but not officially supported) to interact

The Library Code GmbH 2 Feb 09, 2022
A small project in Python + Flask to demonstrate how to create a REST API

SmartBed-RESTApi-Example This application is an example of how to build a REST API. The application os a mock IoT device, simulating a Smart Bed. Impl

Rares Cristea 6 Jan 27, 2022
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.8k Jan 15, 2022
A RESTful whois

whois-rest A RESTful whois. Installation $ pip install poetry $ poetry install $ uvicorn app:app INFO: Started server process [64616] INFO: W

Manabu Niseki 4 Jun 04, 2021
Scaffold django rest apis like a champion 🚀

scaffold django rest apis like a champion 🚀

Abdenasser Elidrissi 77 Jan 19, 2022
Allows simplified Python interaction with Rapid7's InsightIDR REST API.

InsightIDR4Py Allows simplified Python interaction with Rapid7's InsightIDR REST API. InsightIDR4Py allows analysts to query log data from Rapid7 Insi

Micah Babinski 6 Nov 09, 2021