Flask-Smorest

0.47.0 · active · verified Sat Apr 11

Flask-Smorest is a Flask/Marshmallow-based REST API framework that helps build documented REST APIs following the OpenAPI specification. It is currently at version 0.47.0 and maintains an active development pace with consistent minor and patch releases, primarily focusing on bug fixes and new features.

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic Flask application with Flask-Smorest. It defines a simple `Item` resource with a Marshmallow schema, creates endpoints for listing, creating, and retrieving items, and exposes OpenAPI documentation via Swagger UI. Run this Flask app and navigate to `/docs/swagger-ui` to see the generated API documentation.

import os
from flask import Flask
from flask_smorest import Api, Blueprint
from marshmallow import Schema, fields

# 1. Basic Flask app setup
app = Flask(__name__)

# 2. Configuration for Flask-Smorest and OpenAPI
app.config["API_TITLE"] = "Simple Item API"
app.config["API_VERSION"] = "v1"
app.config["OPENAPI_VERSION"] = "3.0.2"
app.config["OPENAPI_URL_PREFIX"] = "/docs"
app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui"
app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY", "super-secret-key-development")

# 3. Initialize Flask-Smorest API
api = Api(app)

# 4. Define a Marshmallow Schema
class ItemSchema(Schema):
    id = fields.Integer(dump_only=True)
    name = fields.String(required=True)
    price = fields.Float(required=True)

# 5. Define a Blueprint
blp = Blueprint("items", __name__, url_prefix="/items", description="Operations on items")

# In-memory store for demonstration
items_db = {}
next_id = 1

# 6. Define API endpoints using the blueprint
@blp.route("/", methods=["POST"])
@blp.arguments(ItemSchema)
@blp.response(201, ItemSchema)
def create_item(new_item_data):
    """Create a new item"""
    global next_id
    new_item_data["id"] = next_id
    items_db[next_id] = new_item_data
    next_id += 1
    return new_item_data

@blp.route("/<int:item_id>", methods=["GET"])
@blp.response(200, ItemSchema)
def get_item(item_id):
    """Get an item by ID"""
    item = items_db.get(item_id)
    if item is None:
        return {"message": "Item not found"}, 404
    return item

@blp.route("/", methods=["GET"])
@blp.response(200, ItemSchema(many=True))
def get_all_items():
    """Get all items"""
    return list(items_db.values())

# 7. Register the blueprint with the API
api.register_blueprint(blp)

# Add a simple root route for testing if desired
@app.route("/")
def hello():
    return "Hello from Flask-Smorest API! Visit /docs/swagger-ui for API documentation."

view raw JSON →