Skip to main content

A lightweight web API framework based on Flask and marshmallow-code projects.

Project description

APIFlask

Build status codecov

APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects. It's easy to use, highly customizable, ORM/ODM-agnostic, and 100% compatible with the Flask ecosystem. It starts as a fork of APIFairy and is inspired by flask-smorest and FastAPI (see Comparison and Motivations for the comparison between these projects).

With APIFlask, you will have:

  • More sugars for view function (@input(), @output(), @app.get(), @app.post() and more)
  • Automatic request validation and deserialization (with Webargs)
  • Automatic response formatting and serialization (with Marshmallow)
  • Automatic OpenAPI Specification (OAS, formerly Swagger Specification) document generation (with APISpec)
  • Automatic interactive API documentation (with Swagger UI and Redoc)
  • API authentication support (with Flask-HTTPAuth)
  • Automatic JSON response for HTTP errors

Currently this project is in active development stage, bugs and breaking changes are expected. Welcome to leave any suggestions or feedbacks in this issue or just submit a pull request to improve it. Thank you!

Requirements

  • Python 3.7+
  • Flask 1.1.0+

Installation

For Linux and macOS:

$ pip3 install apiflask

For Windows:

> pip install apiflask

Links

Example

from apiflask import APIFlask, Schema, input, output, abort
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf

app = APIFlask(__name__)

pets = [
    {
        'id': 0,
        'name': 'Kitty',
        'category': 'cat'
    },
    {
        'id': 1,
        'name': 'Coco',
        'category': 'dog'
    }
]


class PetInSchema(Schema):
    name = String(required=True, validate=Length(0, 10))
    category = String(required=True, validate=OneOf(['dog', 'cat']))


class PetOutSchema(Schema):
    id = Integer()
    name = String()
    category = String()


@app.get('/')
def say_hello():
    # returning a dict equals to use jsonify()
    return {'message': 'Hello!'}


@app.get('/pets/<int:pet_id>')
@output(PetOutSchema)
def get_pet(pet_id):
    if pet_id > len(pets) - 1:
        abort(404)
    # you can also return an ORM/ODM model class instance directly
    return pets[pet_id]


@app.put('/pets/<int:pet_id>')
@input(PetInSchema)
@output(PetOutSchema)
def update_pet(pet_id, data):
    # the parsed input data (dict) will be injected into the view function
    if pet_id > len(pets) - 1:
        abort(404)
    data['id'] = pet_id
    pets[pet_id] = data
    return pets[pet_id]
Click to see the same example with class-based views.
from apiflask import APIFlask, Schema, input, output, abort
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf
from flask.views import MethodView

app = APIFlask(__name__)

pets = [
    {
        'id': 0,
        'name': 'Kitty',
        'category': 'cat'
    },
    {
        'id': 1,
        'name': 'Coco',
        'category': 'dog'
    }
]


class PetInSchema(Schema):
    name = String(required=True, validate=Length(0, 10))
    category = String(required=True, validate=OneOf(['dog', 'cat']))


class PetOutSchema(Schema):
    id = Integer()
    name = String()
    category = String()


# use the "route" decorator to decorate the view class
@app.route('/')
class Hello(MethodView):

    # use HTTP method name as class method name
    def get(self):
        return {'message': 'Hello!'}


@app.route('/pets/<int:pet_id>')
class Pet(MethodView):

    @output(PetOutSchema)
    def get(self, pet_id):
        if pet_id > len(pets) - 1:
            abort(404)
        return pets[pet_id]

    @input(PetInSchema)
    @output(PetOutSchema)
    def put(self, pet_id, data):
        if pet_id > len(pets) - 1:
            abort(404)
        data['id'] = pet_id
        pets[pet_id] = data
        return pets[pet_id]

Save the file as app.py, then run it with:

$ flask run

Now visit the interactive API documentation (Swagger UI) at http://localhost:5000/docs:

Or you can visit the alternative API documentation (Redoc) at http://localhost:5000/redoc:

The auto-generated OpenAPI spec file is available at http://localhost:5000/openapi.json.

For a more complete example, see /examples.

Relationship with Flask

APIFlask is a thin wrapper on top of Flask, you only need to remember four differences (see Migrating from Flask for more details):

  • When creating an application instance, use APIFlask instead of Flask.
  • When creating a blueprint instance, use APIBlueprint instead of Blueprint.
  • The abort() function from APIFlask (apiflask.abort) returns JSON error response.
  • The view class should be registered with the route decorator.

For a minimal Flask application:

from flask import Flask, request, escape

app = Flask(__name__)

@app.route('/')
def hello():
    name = request.args.get('name', 'Human')
    return f'Hello, {escape(name)}'

Now change to APIFlask:

from apiflask import APIFlask  # step one
from flask import request, escape

app = APIFlask(__name__)  # step two

@app.route('/')
def hello():
    name = request.args.get('name', 'Human')
    return f'Hello, {escape(name)}'

In a word, to make Web API development in Flask more easily, APIFlask provides APIFlask and APIBlueprint to extend Flask's Flask and Blueprint objects, and it also ships with some helpful utilities. Other than that, you are actually using Flask.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

APIFlask-0.5.0.tar.gz (56.8 kB view details)

Uploaded Source

Built Distribution

APIFlask-0.5.0-py3-none-any.whl (40.4 kB view details)

Uploaded Python 3

File details

Details for the file APIFlask-0.5.0.tar.gz.

File metadata

  • Download URL: APIFlask-0.5.0.tar.gz
  • Upload date:
  • Size: 56.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.5.0.1 requests/2.25.1 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.8.0

File hashes

Hashes for APIFlask-0.5.0.tar.gz
Algorithm Hash digest
SHA256 d531fef324c0db89c366dde01796b1e9683a7efe44146388052bb8cae7fdfdff
MD5 bf89fabf01d4c0a61ff5167cc097de23
BLAKE2b-256 34e9afad2f46242da7739067162abb585422883ef122cda4a4e536a079e7b94b

See more details on using hashes here.

File details

Details for the file APIFlask-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: APIFlask-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 40.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.5.0.1 requests/2.25.1 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.8.0

File hashes

Hashes for APIFlask-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3c82fb5e7a5cc15f13a09e352db8d97fe2bea061bc89df0f91d16b7adfad4834
MD5 ab0b91c6b5f44af2236bed0acfd5d97e
BLAKE2b-256 ccd6aaa575a79cccb1f3f5f77b468f34c1693a22862f729576cc7b51225192d1

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page