Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate swagger specification file (json) from python using annotations in code?

Problem statement: I want to automate the generation of machine and human readable specifications for JSON APIs so anyone can visualize and interact with our API.
One of the feasible solution is to use OpenAPISpecification (fka swagger). I was not able to find a comprehensible guide to use swagger particularly with tornado, so my questions are:

  1. How can I auto generate swagger specification file from annotations in python code?
  2. I'm also using JSON schemas for input validation, how can I integrate these with swagger specification.

My API is written in python 2.7.11 with tornado 4.3. Please do suggest if you have any other suggestion than using swagger too.

Update: Apispec is an interesting start but it cannot be used with JSON schemas as of now, so doesn't answer my question entirely.

like image 943
AnukuL Avatar asked Aug 14 '26 22:08

AnukuL


1 Answers

we recently had this requirement at work. We made our own generator which generates OpenAPI 3.0 api spec from Google style docstrings. You just need to decorate handlers and model classes. For more info: https://pypi.org/project/tornado-swirl/ -- still a work in progress though but we are actively working on it.

import tornado.web
import tornado_swirl as swirl

@swirl.restapi('/item/(?P<itemid>\d+)')
class ItemHandler(tornado.web.RequestHandler):

    def get(self, itemid):
        """Get Item data.

        Gets Item data from database.

        Path Parameter:
            itemid (int) -- The item id
        """
        pass

@swirl.schema
class User(object):
    """This is the user class

    Your usual long description.

    Properties:
        name (string) -- required.  Name of user
        age (int) -- Age of user

    """
    pass



def make_app():
    return swirl.Application(swirl.api_routes())

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
like image 79
Rodolfo Narciso Duldulao Jr. Avatar answered Aug 18 '26 00:08

Rodolfo Narciso Duldulao Jr.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!