Is there a way to automatically generate REST API JSON description from Bottle routes

强颜欢笑 提交于 2020-01-05 09:32:05

问题


In case of I'm having this code:

class MyApp():
    def __init__(self):
        self.bottle = Bottle()
        self.bottle.route('/')(self.show_api)
        self.bottle.route('/api/')(self.show_api)
        self.bottle.route('/api/item', method='PUT')(self.save_item)

    def show_api(self):
        return <JSON representation of the API?>

Is it possible to get a REST API documentation in JSON format from that? fro some reason self.bottle.routes didn't return anything useful.

Thanks!


回答1:


Actually the right way to generate the JSON API description seems to be:

from collections import defaultdict
import json

def show_api(self):
    api_dict = defaultdict(dict)

    for route in self.bottle.routes:
        api_dict[route.rule]['url'] = 'http://myhost:port{}'.format(route.rule)
        api_dict[route.rule]['method'] = route.method

        # additional config params
        for key in route.config:
            api_dict[route.rule][key] = route.config[key]

    return json.dumps(api_dict)



回答2:


Bottle.route() is meant to be used as a decorator:

@app.route('/hello/:name')
def hello(name):
    return 'Hello %s' % name

So it does return something useful: the decorated function.

You can then use app.routes to get a list of declared routes.

print(app.routes)

Output:

[<GET '/hello/:name' <function hello at 0x7f4137192e18>>]

A function is not directly JSON serializable. But you could easily use str to get a string represenation.



来源:https://stackoverflow.com/questions/27412784/is-there-a-way-to-automatically-generate-rest-api-json-description-from-bottle-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!