All Projects → greyli → apiflask

greyli / apiflask

Licence: MIT License
A lightweight Python web API framework.

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to apiflask

Fastapi
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Stars: ✭ 39,588 (+8856.56%)
Mutual labels:  openapi, swagger-ui, redoc, openapi3
Springdoc Openapi
Library for OpenAPI 3 with spring-boot
Stars: ✭ 1,113 (+151.81%)
Mutual labels:  openapi, swagger-ui, openapi3
Apispec
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..
Stars: ✭ 831 (+88.01%)
Mutual labels:  openapi, marshmallow, openapi3
Openapi Viewer
Browse and test a REST API described with the OpenAPI 3.0 Specification
Stars: ✭ 82 (-81.45%)
Mutual labels:  openapi, swagger-ui, openapi3
asymmetric
Ridiculously fast and easy module-to-API transformations. Learn in minutes, implement in seconds. Batteries included.
Stars: ✭ 35 (-92.08%)
Mutual labels:  openapi, swagger-ui, redoc
Swagger Ui
Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
Stars: ✭ 21,279 (+4714.25%)
Mutual labels:  openapi, swagger-ui, openapi3
Uvicorn Gunicorn Fastapi Docker
Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.
Stars: ✭ 1,014 (+129.41%)
Mutual labels:  openapi, swagger-ui, openapi3
Redoc
📘 OpenAPI/Swagger-generated API Reference Documentation
Stars: ✭ 15,935 (+3505.2%)
Mutual labels:  openapi, redoc, openapi3
Drf Yasg
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.
Stars: ✭ 2,523 (+470.81%)
Mutual labels:  openapi, swagger-ui, redoc
Rapipdf
PDF generation from OpenAPI / Swagger Spec
Stars: ✭ 132 (-70.14%)
Mutual labels:  openapi, swagger-ui, openapi3
Angular Swagger Ui
An angularJS implementation of Swagger UI
Stars: ✭ 131 (-70.36%)
Mutual labels:  openapi, swagger-ui, openapi3
openapi-viewer
Browse and test a REST API described with the OpenAPI 3.0 Specification
Stars: ✭ 85 (-80.77%)
Mutual labels:  openapi, swagger-ui, openapi3
Flasgger
Easy OpenAPI specs and Swagger UI for your Flask API
Stars: ✭ 2,825 (+539.14%)
Mutual labels:  openapi, marshmallow, swagger-ui
cakephp-swagger-bake
Automatically generate OpenAPI, Swagger, and Redoc documentation from your existing CakePHP code.
Stars: ✭ 48 (-89.14%)
Mutual labels:  openapi, swagger-ui, redoc
openapimux
Open API router in go
Stars: ✭ 21 (-95.25%)
Mutual labels:  openapi, openapi3
nexmo-oas-renderer
Render your API references, Nexmo-style!
Stars: ✭ 40 (-90.95%)
Mutual labels:  openapi, openapi3
Tavis.OpenApi
Parser for OpenAPI Specification
Stars: ✭ 18 (-95.93%)
Mutual labels:  openapi, openapi3
swaggerhub-cli
SwaggerHub CLI
Stars: ✭ 28 (-93.67%)
Mutual labels:  openapi, openapi3
openapi-petstore
The pet store sample
Stars: ✭ 35 (-92.08%)
Mutual labels:  openapi, openapi3
light-rest-4j
A RESTful framework built on top of light-4j with both Swagger 2.0 and OpenAPI 3.0 supports
Stars: ✭ 113 (-74.43%)
Mutual labels:  openapi, openapi3

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.

With APIFlask, you will have:

  • More sugars for view function (@app.input(), @app.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

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, 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>')
@app.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
    # APIFlask will serialize the object into JSON format
    return pets[pet_id]


@app.patch('/pets/<int:pet_id>')
@app.input(PetInSchema(partial=True))
@app.output(PetOutSchema)
def update_pet(pet_id, data):
    # the validated and parsed input data will
    # be injected into the view function as a dict
    if pet_id > len(pets) - 1:
        abort(404)
    for attr, value in data.items():
        pets[pet_id][attr] = value
    return pets[pet_id]

Notice: The input, output, doc, and auth_required decorators are now bound to application/blueprint instances, use standalone decorators if you are still using APIFlask < 0.12, see here for more details.

You can also use class-based views with MethodView
from apiflask import APIFlask, Schema, 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):

    @app.output(PetOutSchema)
    def get(self, pet_id):
        """Get a pet"""
        if pet_id > len(pets) - 1:
            abort(404)
        return pets[pet_id]

    @app.input(PetInSchema(partial=True))
    @app.output(PetOutSchema)
    def patch(self, pet_id, data):
        """Update a pet"""
        if pet_id > len(pets) - 1:
            abort(404)
        for attr, value in data.items():
            pets[pet_id][attr] = value
        return pets[pet_id]
Or use async def with Flask 2.0
$ pip install -U flask[async]
import asyncio

from apiflask import APIFlask

app = APIFlask(__name__)


@app.get('/')
async def say_hello():
    await asyncio.sleep(1)
    return {'message': 'Hello!'}

See Using async and await for the details of the async support in Flask 2.0.

Save this as app.py, then run it with :

$ flask run --reload

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. You can also get the spec with the flask spec command:

$ flask spec

For some complete examples, 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.

Relationship with marshmallow

APIFlask accepts marshmallow schema as data schema, uses webargs to validate the request data against the schema, and uses apispec to generate the OpenAPI representation from the schema.

You can build marshmallow schemas just like before, but APIFlask also exposes some marshmallow APIs for convenience (it's optional, you can still import everything from marshamallow directly):

  • apiflask.Schema: The base marshmallow schema class.
  • apiflask.fields: The marshmallow fields, contain the fields from both marshmallow and Flask-Marshmallow. Beware that the aliases (Url, Str, Int, Bool, etc.) were removed (vote in marshmallow #1828 to remove these aliases from marshmallow).
  • apiflask.validators: The marshmallow validators (vote in marshmallow #1829 for better names for validate-related APIs in marshmallow).
from apiflask import Schema
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf
from marshmallow import pre_load, post_dump, ValidationError

Credits

APIFlask starts as a fork of APIFairy and is inspired by flask-smorest and FastAPI (see Comparison and Motivations for the comparison between these projects).

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].