Flask extension that takes care of API representation and authentication.

Related tags

Flaskflask-api-utils
Overview

Flask-API-Utils

https://travis-ci.org/marselester/flask-api-utils.png

Flask-API-Utils helps you to create APIs. It makes responses in appropriate formats, for instance, JSON. All you need to do is to return dictionary from your views. Another useful feature is an authentication. The library supports Hawk HTTP authentication scheme and Flask-Login extension. To sum up, there is an API example project.

"Accept" Header based Response

ResponsiveFlask tends to make responses based on Accept request-header (RFC 2616). If a view function does not return a dictionary, then response will be processed as usual. Here is an example.

from api_utils import ResponsiveFlask

app = ResponsiveFlask(__name__)


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


def dummy_xml_formatter(*args, **kwargs):
    return '<hello>world</hello>'

xml_mimetype = 'application/vnd.company+xml'
app.response_formatters[xml_mimetype] = dummy_xml_formatter

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

It's assumed that file was saved as api.py:

$ python api.py
 * Running on http://127.0.0.1:5000/

Here are curl examples with different Accept headers:

$ curl http://127.0.0.1:5000/ -i
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 22
Server: Werkzeug/0.9.4 Python/2.7.5
Date: Sat, 07 Dec 2013 14:01:14 GMT

{
  "hello": "world"
}
$ curl http://127.0.0.1:5000/ -H 'Accept: application/vnd.company+xml' -i
HTTP/1.0 200 OK
Content-Type: application/vnd.company+xml; charset=utf-8
Content-Length: 20
Server: Werkzeug/0.9.4 Python/2.7.5
Date: Sat, 07 Dec 2013 14:01:50 GMT

<hello>world</hello>
$ curl http://127.0.0.1:5000/ -H 'Accept: blah/*' -i
HTTP/1.0 406 NOT ACCEPTABLE
Content-Type: application/json
Content-Length: 83
Server: Werkzeug/0.9.4 Python/2.7.5
Date: Sat, 07 Dec 2013 14:02:23 GMT

{
  "mimetypes": [
    "application/json",
    "application/vnd.company+xml"
  ]
}

HTTP Error Handling

You can set HTTP error handler by using @app.default_errorhandler decorator. Note that it might override already defined error handlers, so you should declare it before them.

from flask import request
from api_utils import ResponsiveFlask

app = ResponsiveFlask(__name__)


@app.default_errorhandler
def werkzeug_default_exceptions_handler(error):
    error_info_url = (
        'http://developer.example.com/errors.html#error-code-{}'
    ).format(error.code)

    response = {
        'code': error.code,
        'message': str(error),
        'info_url': error_info_url,
    }
    return response, error.code


@app.errorhandler(404)
def page_not_found(error):
    return {'error': 'This page does not exist'}, 404


class MyException(Exception):
    pass


@app.errorhandler(MyException)
def special_exception_handler(error):
    return {'error': str(error)}


@app.route('/my-exc')
def hello_my_exception():
    raise MyException('Krivens!')


@app.route('/yarr')
def hello_bad_request():
    request.args['bad-key']

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

Let's try to curl this example. First response shows that we redefined default {'code': 400, 'message': '400: Bad Request'} error format. Next ones show that you can handle specific errors as usual.

$ curl http://127.0.0.1:5000/yarr -i
HTTP/1.0 400 BAD REQUEST
Content-Type: application/json
Content-Length: 125
Server: Werkzeug/0.9.4 Python/2.7.5
Date: Sun, 29 Dec 2013 14:26:30 GMT

{
  "code": 400,
  "info_url": "http://developer.example.com/errors.html#error-code-400",
  "message": "400: Bad Request"
}
$ curl http://127.0.0.1:5000/ -i
HTTP/1.0 404 NOT FOUND
Content-Type: application/json
Content-Length: 41
Server: Werkzeug/0.9.4 Python/2.7.5
Date: Sun, 29 Dec 2013 14:28:46 GMT

{
  "error": "This page does not exist"
}
$ curl http://127.0.0.1:5000/my-exc -i
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 25
Server: Werkzeug/0.9.4 Python/2.7.5
Date: Sun, 29 Dec 2013 14:27:33 GMT

{
  "error": "Krivens!"
}

Authentication

Hawk extension provides API authentication for Flask.

Hawk is an HTTP authentication scheme using a message authentication code (MAC) algorithm to provide partial HTTP request cryptographic verification.

The extension is based on Mohawk, so make sure you have installed it.

$ pip install mohawk

Usage example:

from flask import Flask
from api_utils import Hawk

app = Flask(__name__)
hawk = Hawk(app)


@hawk.client_key_loader
def get_client_key(client_id):
    # In a real project you will likely use some storage.
    if client_id == 'Alice':
        return 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn'
    else:
        raise LookupError()


@app.route('/')
@hawk.auth_required
def index():
    return 'hello world'

if __name__ == '__main__':
    app.run()
$ curl http://127.0.0.1:5000/ -i
HTTP/1.0 401 UNAUTHORIZED
...

Cookie based authentication is disabled by default. Set HAWK_ALLOW_COOKIE_AUTH = True to enable it. Also Hawk supports response signing, enable it HAWK_SIGN_RESPONSE = True if you need it.

Following configuration keys are used by Mohawk library.

HAWK_ALGORITHM = 'sha256'
HAWK_ACCEPT_UNTRUSTED_CONTENT = False
HAWK_LOCALTIME_OFFSET_IN_SECONDS = 0
HAWK_TIMESTAMP_SKEW_IN_SECONDS = 60

Check Mohawk documentation for more information.

It can be convenient to globally turn off authentication when unit testing by setting HAWK_ENABLED = False.

Tests

Tests are run by:

$ pip install -r requirements.txt
$ tox
Owner
Marsel Mavletkulov
I care about architecture and code quality. I like to design web services (APIs) and reason about their boundaries.
Marsel Mavletkulov
SeCl - A really easy to deploy and use made-on Flask API to manage your files remotely from Terminal

SeCl SeCl it's a really easy to deploy and use made-on Flask API to manage your

ZSendokame 3 Jan 15, 2022
OpenTracing instrumentation for the Flask microframework

Flask-OpenTracing This package enables distributed tracing in Flask applications via The OpenTracing Project. Once a production system contends with r

3rd-Party OpenTracing API Contributions 133 Dec 19, 2022
Python3🐍 webApp to display your current playing music on OBS Studio.

Spotify Overlay A Overlay to display on Obs Studio or any related video/stream recorder, the current music that is playing on your Spotify. Installati

carlitos 0 Oct 17, 2022
Flask Application Structure with MongoDB

This application aims to serve as a template for APIs that intend to use mongoengine and flask-restx

Tiago Franco 5 Jun 25, 2022
Library books management program, built with Flask, Python

Library books management program, With many features and good User Interface. built with Flask, Python. (Include Screenshots) and documentation on how to run it! Thank you :)

Thierry Mugisha 1 May 03, 2022
Geometry Dash Song Bypass with Python Flask Server

Geometry Dash Song Bypass with Python Flask Server

pixelsuft‮ 1 Nov 16, 2021
Paid roles for discord using Stripe, Python, Flask & Docker

Welcome to Paycord Paid roles for discord using Stripe, Python, Flask & Docker. Setup Production On stripe dashboard, go Developers ➡️ Webhooks ➡️ Add

Ward 12 Dec 28, 2022
An python flask app with webserver example

python-flask-example-keepalive How it works? Basically its just a python flask webserver which can be used to keep any repl/herokuapp or any other ser

KangersHub 2 Sep 28, 2022
A gRpc server like Flask (像Flask一样的gRpc服务)

Mask A gRpc server just like Flask. Install Mask support pypi packages, you can simply install by: pip install mask Document Mask manual could be fou

吴东 16 Jun 14, 2022
Flaskr: Intro to Flask, Test-Driven Development (TDD), and JavaScript

Flaskr - Intro to Flask, Test-Driven Development, and JavaScript Share on Twitter As many of you know, Flaskr -- a mini-blog-like-app -- is the app th

Michael Herman 2.2k Jan 04, 2023
Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development.

Flask-Starter Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development. It has all the r

Kundan Singh 259 Dec 26, 2022
A Flask application for Subdomain Enumeration

subdomainer-flask A Flask application for Subdomain Enumeration steps to be done git clone https://github.com/gokulapap/subdomainer-flask pip3 install

GOKUL A.P 7 Sep 22, 2022
A Microsub server built with Python Flask and SQLite.

Microsub Server This repository contains the code that powers my personal Microsub server. Microsub is an IndieWeb specification currently in developm

jamesg 8 Oct 26, 2022
A Python chat app built with Flask that runs in the browser.

A Python chat app built with Flask that runs in the browser. Designed for local area networks that are not connected to the Internet.

Leonard Kleber 1 Dec 23, 2021
A Flask extension that enables or disables features based on configuration.

Flask FeatureFlags This is a Flask extension that adds feature flagging to your applications. This lets you turn parts of your site on or off based on

Rachel Greenfield 131 Sep 26, 2022
Another redis monitor by using flask, angular, socket.io

RedisPAPA we use redis info to monitor the redis usage. PAPA means a father who is monitoring the redis. accoding to the redis doc, it is be recommand

no13bus 393 Dec 30, 2022
Forum written for learning purposes in flask and sqlalchemy

Flask-forum forum written for learning purposes using SQLalchemy and flask How to install install requirements pip install sqlalchemy flask clone repo

Kamil 0 May 23, 2022
Flask-redmail - Email sending for Flask

Flask Red Mail: Email Sending for Flask Flask extension for Red Mail What is it?

Mikael Koli 11 Sep 23, 2022
Sample Dockerized flask app deployed on Kubernetes on Azure using AKS

Sample Dockerized flask app deployed on Kubernetes on Azure using AKS

Ahmed khémiri 22 Sep 08, 2021
A Flask wrapper of Starknet state. Similar in purpose to Ganache.

Introduction A Flask wrapper of Starknet state. Similar in purpose to Ganache. Aims to mimic Starknet's Alpha testnet, but with simplified functionali

Shard Labs 159 Jan 04, 2023