Skip to content

Instantly share code, notes, and snippets.

@jslvtr
Created January 18, 2023 18:26
Show Gist options
  • Save jslvtr/0c3d8ea4360c02fa6c025a586ec4948f to your computer and use it in GitHub Desktop.
Save jslvtr/0c3d8ea4360c02fa6c025a586ec4948f to your computer and use it in GitHub Desktop.
Barebones Flask-Smorest API showing filtering with query string arguments
from flask import Flask
from flask.views import MethodView
from marshmallow import Schema, fields
from flask_sqlalchemy import SQLAlchemy
from flask_smorest import Api, Blueprint
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config["API_TITLE"] = "Stores REST API"
app.config["API_VERSION"] = "v1"
app.config["OPENAPI_VERSION"] = "3.0.3"
app.config["OPENAPI_URL_PREFIX"] = "/"
app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui"
app.config["OPENAPI_SWAGGER_UI_URL"] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/"
db = SQLAlchemy(app)
api = Api(app)
blp = Blueprint("blp", __name__)
class StoreModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
with app.app_context():
db.create_all()
class StoreSchema(Schema):
id = fields.Integer(dump_only=True)
name = fields.String(required=True)
class StoreSearchQueryArgs(Schema):
name = fields.String()
@blp.route("/store")
class StoreList(MethodView):
@blp.arguments(StoreSearchQueryArgs, location="query")
@blp.response(200, StoreSchema(many=True))
def get(self, search_values):
return StoreModel.query.filter(StoreModel.name.startswith(search_values.get("name", ""))).all()
@blp.arguments(StoreSchema)
@blp.response(201, StoreSchema)
def post(self, new_store):
store = StoreModel(**new_store)
db.session.add(store)
db.session.commit()
return store
api.register_blueprint(blp)
flask
flask-smorest
flask-sqlalchemy
marshmallow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment