Giter VIP home page Giter VIP logo

apiflask's Introduction

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, and 100% compatible with the Flask ecosystem. It starts as a fork of APIFairy and is inspired by 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_json
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_json(404)
    # you can also return an ORM 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_json(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 two differences:

  • When creating an application instance, use APIFlask instead of Flask.
  • When creating a blueprint instance, use APIBlueprint instead of Blueprint.

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.

apiflask's People

Contributors

180909 avatar greyli avatar johntheprime avatar miguelgrinberg avatar yuxiaoy1 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.