Type Stubs for flask-smorest

1.1.2 · active · verified Sat Apr 11

types-smorest provides PEP 561 compatible type stubs for the `flask-smorest` library, a REST API framework built upon Flask and Marshmallow. It allows static type checkers like MyPy to perform type verification on `flask-smorest` applications, enhancing code quality and maintainability. The library is currently at version 1.1.2 and receives updates as needed to track `flask-smorest` features and fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic `flask-smorest` application. Installing `types-smorest` alongside `flask-smorest` allows static type checkers like MyPy to analyze this code for type consistency. The stubs provide type information for `Api`, `Blueprint`, and other `flask-smorest` constructs, ensuring that method arguments, return types, and decorator usage are correctly typed according to `flask-smorest`'s API.

from flask import Flask
from flask.views import MethodView
from marshmallow import Schema, fields
from flask_smorest import Api, Blueprint, abort

app = Flask(__name__)
app.config["API_TITLE"] = "My API"
app.config["API_VERSION"] = "v1"
app.config["OPENAPI_VERSION"] = "3.0.2"

api = Api(app)

class ItemSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.String(required=True)
    price = fields.Float(required=True)

blp = Blueprint("items", "items", url_prefix="/items", description="Operations on items")
api.register_blueprint(blp)

@blp.route("/")
class Items(MethodView):
    @blp.response(200, ItemSchema(many=True))
    def get(self) -> list[dict]:
        """List all items"""
        # In a real app, this would fetch from a database
        items = [{
            "id": 1,
            "name": "Example Item",
            "price": 10.99
        }]
        return items

    @blp.arguments(ItemSchema)
    @blp.response(201, ItemSchema)
    def post(self, new_item_data: dict) -> dict:
        """Create a new item"""
        # In a real app, this would save to a database
        new_item_data['id'] = len(self.get()) + 1 # Simulate ID generation
        return new_item_data

# To run this example (requires flask-smorest, marshmallow):
# 1. pip install Flask flask-smorest marshmallow
# 2. Save as app.py
# 3. export FLASK_APP=app.py
# 4. flask run
#
# To use with type checking (requires types-smorest, mypy):
# 1. pip install types-smorest mypy
# 2. mypy app.py

view raw JSON →