Skip to content

Instantly share code, notes, and snippets.

@mthipparthi
Created January 17, 2019 11:47
Show Gist options
  • Save mthipparthi/ad85633a513e2acdd6c3019f887b51c0 to your computer and use it in GitHub Desktop.
Save mthipparthi/ad85633a513e2acdd6c3019f887b51c0 to your computer and use it in GitHub Desktop.
from flask import Flask
from flask_apispec import use_kwargs, marshal_with
from marshmallow import fields, Schema
from flask import make_response
from flask_apispec.views import MethodResource
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_apispec.extension import FlaskApiSpec
app = Flask(__name__)
class PetSchema(Schema):
pet_id = fields.Str(required=False)
name = fields.Str(required=False)
category = fields.Str(required=False)
size = fields.Str(required=False)
pet = {"pet_id": 100, "name": "pet1", "category":"category1", "size" :"size1"}
pets = [ { "pet_id": 100, "name": "pet1", "category":"category1", "size" :"size1"},
{"pet_id": 200, "name": "pet2", "category":"category2", "size" :"size2"}]
@app.route('/pets')
@marshal_with(PetSchema(many=True))
def get_pets(**kwargs):
return pets
class PetResource(MethodResource):
@use_kwargs({"pet_id": fields.Str(required=True)}, locations=["query"])
@marshal_with(PetSchema)
def get(self, pet_id):
return pet
@use_kwargs(PetSchema)
@marshal_with(PetSchema, code=201)
def post(self, **kwargs):
return pet
@use_kwargs({"pet_id": fields.Str(required=True)}, locations=["query"])
@marshal_with(PetSchema)
def put(self, pet_id, **kwargs):
return pet
@use_kwargs({"pet_id": fields.Str(required=True)}, locations=["query"])
@marshal_with(None, code=204)
def delete(self, pet_id):
return make_response('', 204)
app.config.update({
'APISPEC_SPEC': APISpec(
title='pets',
version='v1',
plugins=[MarshmallowPlugin()],
),
'APISPEC_SWAGGER_URL': '/swagger/',
})
docs = FlaskApiSpec(app)
docs.register(get_pets)
app.add_url_rule('/pet', view_func=PetResource.as_view(PetResource.__name__.lower()) )
# with app.app_context():
docs.register(PetResource)
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment