Skip to main content

A successful practice combining flask_restx with marshmallow

Project description

Flask-RESTX-marshmallow

Flask-RESTX-marshmallow is an extension for Flask and Flask-RESTX, which is a successful practice combining flask_restx with marshmallow.

Compatibility

Flask-RESTX-marshmallow requires Python 3.10+.

Installation

Install the extension with pip:

pip install flask-restx-marshmallow

or with poetry:

poetry add flask-restx-marshmallow

Quickstart

With Flask-RESTX-marshmallow, you only import the api instance to route and document your endpoints.

import uuid

import sqlalchemy as sa
from flask import Flask
from marshmallow import fields, post_load

from flask_restx_marshmallow import (
    Api,
    JSONParameters,
    QueryParameters,
    Resource,
    SQLAlchemy,
    StandardSchema,
)

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
api = Api(
    app,
    version="0.1.1",
    title="example API",
    description="api interface for example app",
)
db = SQLAlchemy(app)
ns = api.namespace("example", description="example operations")


class Task(db.Model):
    id = db.Column(db.String(32), primary_key=True)
    task = db.Column(db.String(80))

    def __init__(self, id, task):
        self.id = id.hex
        self.task = task

    def __repr__(self):
        return "<Task %r>" % self.task


class QueryTaskParameters(QueryParameters):
    id = fields.UUID(metadata={"description": "The task unique identifier"})

    @post_load
    def process(self, data, **_kwargs):
        if "id" in data:
            return {"data": Task.query.filter_by(id=data["id"].hex).first()}
        return {"code": 1, "message": "id is required", "success": False}


class CreateTaskParameters(JSONParameters):
    task = fields.String(
        required=True, metadata={"description": "The task details"}
    )

    @post_load
    def process(self, data, **_kwargs):
        try:
            task = Task(id=uuid.uuid4(), task=data["task"])
            db.session.add(task)
        except sa.exc.IntegrityError as e:
            db.session.rollback()
            return {"code": 1, "message": str(e), "success": False}
        else:
            db.session.commit()
            return {
                "message": f"create task success with id {uuid.UUID(task.id)}"
            }


class TaskSchema(StandardSchema):
    data = fields.Nested(
        {
            "id": fields.UUID(
                metadata={"description": "The task unique identifier"},
            ),
            "task": fields.String(metadata={"description": "The task details"}),
        }
    )


@ns.route("/")
class TaskManage(Resource):
    """task manage"""

    @ns.parameters(params=QueryTaskParameters(), location="query")
    @ns.response(
        code=200,
        description="query task by id",
        model=TaskSchema(message="query task success"),
    )
    def get(self, task):
        """query task by id"""
        return task

    @ns.parameters(params=CreateTaskParameters(), location="body")
    @ns.response(
        code=200,
        description="create a new task",
        model=None,
        name="CreateSchema",
        message="create successfully",
    )
    def post(self, res):
        """create a new task"""
        return res


if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    api.register_doc(app)
    app.run(debug=True)

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_restx_marshmallow-0.1.1.tar.gz (475.6 kB view details)

Uploaded Source

Built Distribution

flask_restx_marshmallow-0.1.1-py3-none-any.whl (473.0 kB view details)

Uploaded Python 3

File details

Details for the file flask_restx_marshmallow-0.1.1.tar.gz.

File metadata

  • Download URL: flask_restx_marshmallow-0.1.1.tar.gz
  • Upload date:
  • Size: 475.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.12 CPython/3.10.6 Linux/5.15.90.1-microsoft-standard-WSL2

File hashes

Hashes for flask_restx_marshmallow-0.1.1.tar.gz
Algorithm Hash digest
SHA256 ca5d4ab946254371cfdb492784d00aa2e822435645017814a69e3ffc0dd209ef
MD5 fd3e5e3f5e9983aecea4b91323786891
BLAKE2b-256 8977b59314d223ffdc3959bc76e18cb54d590b66feda4d638519f2bfad7fa0af

See more details on using hashes here.

File details

Details for the file flask_restx_marshmallow-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for flask_restx_marshmallow-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 caddb1c2144123c2c28dde40d5b2c63f85c6b0a834c68cd3ee75a81ffdffcdf3
MD5 4fcf6e8afd7783383de7df243107cb26
BLAKE2b-256 de6202769f66d0ab9bb17e2b730779f157df101344ac7dd5baccad7510bf0d68

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