Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Swagger spec extractor for flask-restful

License

NotificationsYou must be signed in to change notification settings

purepy/flask-restful-swagger-3.0

 
 

Repository files navigation

Build Status

What is flask-restful-swagger-2?

flask-restful-swagger-2 is a wrapper forflask-restful whichenablesswagger support according to theswagger 2.0 specification.

This project is based onflask-restful-swagger, but it onlysupported swagger 1.2.

Getting started

Install:

pip install flask-restful-swagger-2

To use it, change your import fromfrom flask_restful import Api tofrom flask_restful_swagger_2 import Api.

fromflaskimportFlask# Instead of using this: from flask_restful import Api# Use this:fromflask_restful_swagger_2importApiapp=Flask(__name__)# Use the swagger Api class as you would use the flask restful class.# It supports several (optional) parameters, these are the defaults:api=Api(app,api_version='0.0',api_spec_url='/api/swagger')

The Api class supports the following parameters:

ParameterDescription
add_api_spec_resourceSet toTrue to add an endpoint to serve the swagger specification (defaults toTrue).
api_versionThe API version string (defaults to '0.0'). Maps to theversion field of theinfo object.
api_spec_baseInstead of specifying individual swagger fields, you can pass in a minimalschema object to use as a template. Note that parameters specified explicity will overwrite the values in this template.
api_spec_urlThe URL path that serves the swagger specification document (defaults to/api/swagger). The path is appended with.json and.html (i.e./api/swagger.json and/api/swagger.html).
base_pathThe base path on which the API is served. Maps to thebasePath field of theschema object.
consumesA list of MIME types the API can consume. Maps to theconsumes field of theschema object.
contactThe contact information for the API. Maps to thecontact field of theinfo object.
descriptionA short description of the application. Maps to thedescription field of theinfo object.
external_docsAdditional external documentation. Maps to theexternalDocs field of theschema object.
hostThe host serving the API. Maps to thehost field of theschema object.
licenseThe license information for the API. Maps to thelicense field of theinfo object.
parametersThe parameters that can be used across operations. Maps to theparameters field of theschema object.
producesA list of MIME types the API can produce. Maps to theproduces field of theschema object.
responsesThe responses that can be used across operations. Maps to theresponses field of theschema object.
schemesThe transfer protocol of the API. Maps the theschemes field of theschema object.
securityThe security schemes for the API as a whole. Maps to thesecurity field of theschema object.
security_definitionsThe security definitions for the API. Maps to thesecurityDefinitions field of theschema object.
tagsA list of tags used by the specification with additional metadata. Maps to thetags field fo theschema object.
termsThe terms of service for the API. Maps to thetermsOfService field of theinfo object.
titleThe title of the application (defaults to the flask app module name). Maps to thetitle field of theinfo object.

Documenting API endpoints

Decorate your API endpoints with@swagger.doc. It takes a dictionary in the format of aswagger operation object.

classUserItemResource(Resource):@swagger.doc({'tags': ['user'],'description':'Returns a user','parameters': [            {'name':'user_id','description':'User identifier','in':'path','type':'integer'            }        ],'responses': {'200': {'description':'User','schema':UserModel,'examples': {'application/json': {'id':1,'name':'somebody'                    }                }            }        }     })defget(self,user_id):# Do some processingreturnUserModel(id=1,name='somebody'}),200# generates json response {"id": 1, "name": "somebody"}

Use add_resource as usual.

api.add_resource(UserItemResource,'/api/users/<int:user_id>')

Parsing query parameters

If a resource function contains the special argument_parser, anyquery type parameters in thedocumentation will be automatically added to a reqparse parser and assigned to the_parser argument.

Using models

Create a model by inheriting fromflask_restful_swagger_2.Schema

fromflask_restful_swagger_2importSchemaclassEmailModel(Schema):type='string'format='email'classKeysModel(Schema):type='object'properties= {'name': {'type':'string'        }    }classUserModel(Schema):type='object'properties= {'id': {'type':'integer','format':'int64',        },'name': {'type':'string'        },'mail':EmailModel,'keys':KeysModel.array()    }required= ['name']

You can build your models according to theswagger schema object specification

It is recommended that you always return a model in your views so that your code and documentation are in sync.

RequestParser support

You can specify RequestParser object if you want to pass its arguments to spec. In such case, there is not need to define model manually

fromflask_restful.reqparseimportRequestParserfromflask_restful_swagger_2importswagger,ResourceclassGroupResource(Resource):post_parser=RequestParser()post_parser.add_argument('name',type=str,required=True)post_parser.add_argument('id',type=int,help='Id of new group')@swagger.doc({'tags': ['groups'],'description':'Adds a group','reqparser': {'name':'group parser','parser':post_parser},'responses': {'201': {'description':'Created group','examples': {'application/json': {'id':1                    }                }            }        }    })defpost(self):    ...

Swagger schema (among other things):

{"GroupsModel": {"properties": {"id": {"default":null,"description":"Id of new group","name":"id","required":false,"type":"integer"            },"name": {"default":null,"description":null,"name":"name","required":true,"type":"string"        }    },"type":"object"}

Using authentication

In the example above, the viewUserItemResource is a subclass ofResource, which is provided byflask_restful. However,flask_restful_swagger_2 provides a thin wrapper aroundResource to provide authentication. By using this, you cannot only prevent access to resources, but also hide the documentation depending on the providedapi_key.

Example:

# Import Api and Resource instead from flask_restful_swagger_2fromflask_restful_swagger_2importApi,swagger,Resourceapi=Api(app)defauth(api_key,endpoint,method):# Space for your fancy authentication. Return True if access is granted, otherwise False# api_key is extracted from the url parameters (?api_key=foo)# endpoint is the full swagger url (e.g. /some/{value}/endpoint)# method is the HTTP methodreturnTrueswagger.auth=authclassMyView(Resource):@swagger.doc({# documentation...    })defget(self):returnSomeModel(value=5)api.add_resource(MyView,'/some/endpoint')

Specification document

Theget_swagger_doc method of the Api instance returns the specification document object,which may be useful for integration with other tools for generating formatted output or client code.

Using Flask Blueprints

To use Flask Blueprints, create a function in your views module that creates the blueprint,registers the resources and returns it wrapped in an Api instance:

fromflaskimportBlueprint,requestfromflask_restful_swagger_2importApi,swagger,ResourceclassUserResource(Resource):...classUserItemResource(Resource):...defget_user_resources():"""    Returns user resources.    :param app: The Flask instance    :return: User resources    """blueprint=Blueprint('user',__name__)api=Api(blueprint,add_api_spec_resource=False)api.add_resource(UserResource,'/api/users')api.add_resource(UserItemResource,'/api/users/<int:user_id>')returnapi

In your initialization module, collect the swagger document objects for eachset of resources, then use theget_swagger_blueprint function to combine thedocuments and specify the URL to serve them at (default is '/api/swagger').Note that theget_swagger_blueprint function accepts the same keyword parametersas theApi class to populate the fields of the combined swagger document.Finally, register the swagger blueprint along with the blueprints for yourresources.

fromflask_restful_swagger_2importget_swagger_blueprint...# A list of swagger document objectsdocs= []# Get user resourcesuser_resources=get_user_resources()# Retrieve and save the swagger document object (do this for each set of resources).docs.append(user_resources.get_swagger_doc())# Register the blueprint for user resourcesapp.register_blueprint(user_resources.blueprint)# Prepare a blueprint to serve the combined list of swagger document objects and register itapp.register_blueprint(get_swagger_blueprint(docs,'/api/swagger',title='Example',api_version='1'))

Refer to the files in theexample folder for the complete code.

Running and testing

To run the example project in theexample folder:

pip install flask-restful-swagger-2pip install flask-cors    # needed to access spec from swagger-uipython app.py

To run the example which uses Flask Blueprints:

python app_blueprint.py

The swagger spec will by default be athttp://localhost:5000/api/swagger.json. You can change the URL by passingapi_spec_url='/my/path' to theApi constructor. You can useswagger-uito explore your api. Try it online athttp://petstore.swagger.io/

To run tests:

python setup.py test

About

A Swagger spec extractor for flask-restful

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python99.7%
  • Makefile0.3%

[8]ページ先頭

©2009-2025 Movatter.jp