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
A live chat built with python(flask + gevent + apscheduler) + redis

a live chat room built with python(flask / gevent / apscheduler) + redis Basic Architecture Screenshot Install cd /path/to/source python bootstrap.py

Limboy 309 Nov 13, 2022
HTTP security headers for Flask

Talisman: HTTP security headers for Flask Talisman is a small Flask extension that handles setting HTTP headers that can help protect against a few co

Google Cloud Platform 853 Dec 19, 2022
Guitar tabs web app for guitar fans, powered by Python/Flask

Guitar123 version 0.8.5 Guitar tabs web app for guitar fans, powered by Python/Flask Features Guitar tabs search and browse Easy to use for end user a

lowrain 48 Dec 27, 2022
REST API with Flask and SQLAlchemy. I would rather not use it anymore.

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 15, 2021
Lightweight library for providing filtering mechanism for your APIs using SQLAlchemy

sqlalchemy-filters-plus is a light-weight extendable library for filtering queries with sqlalchemy. Install pip install sqlalchemy-fitlers-plus Usage

Karami El Mehdi 38 Oct 05, 2022
Seamlessly serve your static assets of your Flask app from Amazon S3

flask-s3 Seamlessly serve the static assets of your Flask app from Amazon S3. Maintainers Flask-S3 is maintained by @e-dard, @eriktaubeneck and @SunDw

Edd Robinson 188 Aug 24, 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
É uma API feita em Python e Flask que pesquisa informações em uma tabela .xlsx e retorna o resultado.

API de rastreamento de pacotes É uma API feita em Python e Flask que pesquisa informações de rastreamento de pacotes em uma tabela .xlsx e retorna o r

Marcos Beraldo Barros 4 Jun 27, 2021
REST API with mongoDB and Flask.

Flask REST API with mongoDB py 3.10 First, to install all dependencies: python -m pip install -r requirements.txt Second, into the ./src/ folder, cop

Luis Quiñones Requelme 3 Mar 05, 2022
Flask app + (html+css+ajax) contain ability add employee and place where employee work - plant or salon

#Manage your employees! With all employee information stored in one place, you no longer have to sift through hoards of spreadsheets to manually searc

Kateryna 1 Dec 22, 2021
Flask app for deploying DigitalOcean droplet using Pulumi.

Droplet Deployer Simple Flask app which deploys a droplet onto Digital ocean. Behind the scenes there's Pulumi being used. Background I have been Terr

Ahmed Sajid 1 Oct 30, 2021
docker-compose uWSGI nginx flask

docker-compose uWSGI nginx flask Note that this was tested on CentOS 7 Usage sudo yum install docker

Abdolkarim Saeedi 3 Sep 11, 2022
WebSocket support for Flask

flask-sock WebSocket support for Flask Installation pip install flask-sock Example from flask import Flask, render_template from flask_sock import Soc

Miguel Grinberg 165 Dec 27, 2022
Rubik's cube assistant on Flask webapp

webcube Rubik's cube assistant on Flask webapp. This webapp accepts the six faces of your cube and gives you the voice instructions as a response. Req

Yash Indane 56 Nov 22, 2022
Set up a modern flask web server by running one command.

Build Flask App · Set up a modern flask web server by running one command. Installing / Getting started pip install build-flask-app Usage build-flask-

Kushagra Bainsla 5 Jul 16, 2022
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 boilerplate Flask API for a Fullstack Project :rocket:

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

Yasser Tahiri 32 Dec 24, 2022
A Fast API style support for Flask. Gives you MyPy types with the flexibility of flask

Flask-Fastx Flask-Fastx is a Fast API style support for Flask. It Gives you MyPy types with the flexibility of flask. Compatibility Flask-Fastx requir

Tactful.ai 18 Nov 26, 2022
Flask webassets integration.

Integrates the webassets library with Flask, adding support for merging, minifying and compiling CSS and Javascript files. Documentation: https://flas

Michael Elsdörfer 433 Dec 29, 2022
Adds Injector support to Flask.

Flask-Injector Adds Injector support to Flask, this way there's no need to use global Flask objects, which makes testing simpler. Injector is a depend

Alec Thomas 246 Dec 28, 2022