└── app.py /app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_restful import Resource, Api 3 | from apispec import APISpec 4 | from marshmallow import Schema, fields 5 | from apispec.ext.marshmallow import MarshmallowPlugin 6 | from flask_apispec.extension import FlaskApiSpec 7 | from flask_apispec.views import MethodResource 8 | from flask_apispec import marshal_with, doc, use_kwargs 9 | 10 | app = Flask(__name__) # Flask app instance initiated 11 | api = Api(app) # Flask restful wraps Flask app around it. 12 | app.config.update({ 13 | 'APISPEC_SPEC': APISpec( 14 | title='Awesome Project', 15 | version='v1', 16 | plugins=[MarshmallowPlugin()], 17 | openapi_version='2.0.0' 18 | ), 19 | 'APISPEC_SWAGGER_URL': '/swagger/', # URI to access API Doc JSON 20 | 'APISPEC_SWAGGER_UI_URL': '/swagger-ui/' # URI to access UI of API Doc 21 | }) 22 | docs = FlaskApiSpec(app) 23 | 24 | 25 | class AwesomeResponseSchema(Schema): 26 | message = fields.Str(default='Success') 27 | 28 | 29 | class AwesomeRequestSchema(Schema): 30 | api_type = fields.String(required=True, description="API type of awesome API") 31 | 32 | 33 | # Restful way of creating APIs through Flask Restful 34 | class AwesomeAPI(MethodResource, Resource): 35 | @doc(description='My First GET Awesome API.', tags=['Awesome']) 36 | @marshal_with(AwesomeResponseSchema) # marshalling 37 | def get(self): 38 | ''' 39 | Get method represents a GET API method 40 | ''' 41 | return {'message': 'My First Awesome API'} 42 | 43 | @doc(description='My First GET Awesome API.', tags=['Awesome']) 44 | @use_kwargs(AwesomeRequestSchema, location=('json')) 45 | @marshal_with(AwesomeResponseSchema) # marshalling 46 | def post(self, **kwargs): 47 | ''' 48 | Get method represents a GET API method 49 | ''' 50 | return {'message': 'My First Awesome API'} 51 | 52 | 53 | api.add_resource(AwesomeAPI, '/awesome') 54 | docs.register(AwesomeAPI) 55 | 56 | if __name__ == '__main__': 57 | app.run(debug=True) 58 | --------------------------------------------------------------------------------