Skip to main content

Flask + marshmallow + OpenAPI

Project description

Overview

PyPI Status license python_versions

Provides OpenAPI documentation generated from code for Flask APIs built around marshmallow schemas.

This hackish and organically grown (TM) package was created because no other similar projects worked exactly the way I wanted them.

You will probably be better served by some other, properly maintained project with similar purpose:

If you still want to use it, welcome aboard :-) and read on!

Installation

pip install flask-marshmallow-openapi

Example

See example application. Following is incomplete excerpt to demonstrate:

import flask
import marshmallow as ma
from flask_marshmallow_openapi import OpenAPI, OpenAPISettings, open_api


class SchemaOpts(ma.SchemaOpts):
    def __init__(self, meta, *args, **kwargs):
        self.tags = getattr(meta, "tags", [])
        self.url_id_field = getattr(meta, "url_id_field", None)
        super().__init__(meta, *args, **kwargs)


class BookSchema(ma.Schema):
    OPTIONS_CLASS = SchemaOpts

    class Meta:
        url_id_field = "id"
        tags = ["Books"]
        description = "Schema for Book model"

    id = ma.fields.Integer(as_string=True)
    title = ma.fields.String(
        allow_none=False, metadata={"description": "book.title description"}
    )
    publisher = ma.fields.String(allow_none=False)
    isbn = ma.fields.String(allow_none=False)


app = flask.Flask(__name__)


@app.route("/books", methods=["GET"])
@open_api.get(BookSchema, "bookList", many=True)
def books_list():
    return "<p>Hello, World!</p>"


@app.route("/books/<int:book_id>", methods=["GET"])
@open_api.get(BookSchema, "bookDetail", many=False)
def books_detail(book_id):
    """
    description: |
        Look I can Markdown!

        | foo | bar | baz |
        | --- | --- | --- |
        | 1   | 2   | 3   |
        | 4   | 5   | 6   |
    """
    return "<p>Hello, World!</p>"


conf = OpenAPISettings(
    api_version="v1",
    api_name="Foobar API",
    app_package_name="foobar_api",
    mounted_at="/v1",
)


docs = OpenAPI(config=conf)
docs.init_app(app)

Serving docs via ngnix

Add collect-static command to your app:

import shutil

import click
import flask

@app.cli.command("collect_static")
@click.argument(
    "destination_dir",
    nargs=1,
    type=click.Path(file_okay=False, dir_okay=True, writable=True, resolve_path=True),
    required=True,
)
def collect_static_command(destination_dir):
    shutil.copytree(
        flask.current_app.static_folder, destination_dir, dirs_exist_ok=True
    )
    docs.collect_static(destination_dir)
    click.echo(f"Static files collected into {destination_dir}.")

Configure nginx:

server {
    # ...

    location ^~ /v1/static {
        alias /home/user/static;
        try_files $uri $uri.html =404;
    }

    location ^~ /v1/docs {
        alias /home/user/static/docs;
        try_files $uri $uri.html =404;
    }

    # ...
}

Whenever deploying app, call:

flask --app foobar_api collect-static /home/user/static

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

flask-marshmallow-openapi-0.1.9.tar.gz (980.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_marshmallow_openapi-0.1.9-py3-none-any.whl (985.7 kB view details)

Uploaded Python 3

File details

Details for the file flask-marshmallow-openapi-0.1.9.tar.gz.

File metadata

File hashes

Hashes for flask-marshmallow-openapi-0.1.9.tar.gz
Algorithm Hash digest
SHA256 f974ab1921bc4107ae2d5f978eadf3d3607001fbb3bc2f713b2e3c10fe4718a4
MD5 abe2d9995a553df2b85dcd82fd8a9dc7
BLAKE2b-256 6d0c15d5198d8842fe8dbd2b57458d03818555c41f3704a0338fc333e8b554d3

See more details on using hashes here.

File details

Details for the file flask_marshmallow_openapi-0.1.9-py3-none-any.whl.

File metadata

File hashes

Hashes for flask_marshmallow_openapi-0.1.9-py3-none-any.whl
Algorithm Hash digest
SHA256 77ef31e4800e1c63c94c732861f70fdf42beab9c761d98983d99097b87214a8f
MD5 82073045b059ddf2d6a213e798e1797b
BLAKE2b-256 c99538bd0987d8b1eea388f03306cde1c34e628d83a1a8e9dca0d93b654082d4

See more details on using hashes here.

Supported by

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