Skip to content

Instantly share code, notes, and snippets.

Created January 18, 2023 18:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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"] = ""
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():
class StoreSchema(Schema):
id = fields.Integer(dump_only=True)
name = fields.String(required=True)
class StoreSearchQueryArgs(Schema):
name = fields.String()
class StoreList(MethodView):
@blp.arguments(StoreSearchQueryArgs, location="query")
@blp.response(200, StoreSchema(many=True))
def get(self, search_values):
return StoreModel.query.filter("name", ""))).all()
@blp.response(201, StoreSchema)
def post(self, new_store):
store = StoreModel(**new_store)
return store
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment