kemingy / flaskerk

A flask extension for api doc and validation of request&response.
https://kemingy.github.io/flaskerk
MIT License
27 stars 2 forks source link

Support for tags and change Swagger layout #32

Open ThiNepo opened 4 years ago

ThiNepo commented 4 years ago

Hello,

First, I have to say that I love the work that you guys are doing with this library. I was already thinking in create validation and automatic OpenAPI documentation similar to what FastAPI is doing.

I have two requests for the current status of Flaskerk.

  1. I would like to change the layout of the Swagger docs in the configs. Since I want to use the "BaseLayout" instead of the "StandaloneLayout". _I could achieve this by creating a custom template folder, changing the swagger.html file and passing "templatefolder" parameter in the constructor, but would be great to be able to choose between different layouts directly in the config.

  2. We need a way to support tags. If you take a look in the code below you will see my current implementation.

from flask import Flask, request, jsonify
from flaskerk import Flaskerk
from pydantic import BaseModel
import os

class Query(BaseModel):
    text: str

app = Flask(__name__)
api = Flaskerk(
    title='Demo Service',
    version='1.0',
    ui='swagger',
    template_folder=os.path.join(os.getcwd(), "templates_api")
)

@app.route('/api/first')
@api.validate(query=Query, tags=["first"])
def first():
    print(request.query)
    return jsonify(label=0)

@app.route('/api/second')
@api.validate(query=Query, tags=["second"])
def second():
    print(request.query)
    return jsonify(label=0)

if __name__ == "__main__":
    api.register(app)
    app.run()

Then in the base.py you should change the validate function for:

def validate(self, query=None, data=None, resp=None, x=[], tags=[]):

Add tags to the validate_request.

# register tags
validate_request.tags = tags

and finally, add them to the spec.

if hasattr(func, 'tags'):                    
    spec['tags'] = func.tags
kemingy commented 4 years ago

Noticed.

I'm also planning to add tags. Looks good to me.

For the swagger layout, the current implementation is in https://github.com/kemingy/flaskerk/blob/34a09880663a00180b1014865e8d7abf68ce7602/flaskerk/view.py#L14 . So I guess the users only need to offer a HTML file with {{spec_url}}. Then it can be rendered by jinja2. Is it ok?

On Tue, Dec 3, 2019, 21:36 ThiNepo notifications@github.com wrote:

Hello,

First, I have to say that I love the work that you guys are doing with this library. I was already thinking in create validation and automatic OpenAPI documentation similar to what FastAPI is doing.

I have two requests for the current status of Flaskerk.

1.

I would like to change the layout of the Swagger docs in the configs. Since I want to use the "BaseLayout" instead of the "StandaloneLayout". I could achieve this by creating a custom template folder, changing the swagger.html file and passing "template_folder" parameter in the constructor, but would be great to be able to choose between different layouts directly in the config. 2.

We need a way to support tags. If you take a look in the code below you will see my current implementation.

from flask import Flask, request, jsonify from flaskerk import Flaskerk from pydantic import BaseModel import os

class Query(BaseModel): text: str

app = Flask(name) api = Flaskerk( title='Demo Service', version='1.0', ui='swagger', template_folder=os.path.join(os.getcwd(), "templates_api") )

@app.route('/api/first') @api.validate(query=Query, tags=["first"]) def first(): print(request.query) return jsonify(label=0)

@app.route('/api/second') @api.validate(query=Query, tags=["second"]) def second(): print(request.query) return jsonify(label=0)

if name == "main": api.register(app) app.run()

Then in the base.py you should change the validate function for:

def validate(self, query=None, data=None, resp=None, x=[], tags=[]):

Add tags to the validate_request.

register tags

validate_request.tags = tags

and finally, add them to the spec.

if hasattr(func, 'tags'): spec['tags'] = func.tags

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/kemingy/flaskerk/issues/32?email_source=notifications&email_token=ADC7UXLXITF44EQWEUMZJ4TQWZOFLA5CNFSM4JUYEDX2YY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4H5VQUGQ, or unsubscribe https://github.com/notifications/unsubscribe-auth/ADC7UXIOKWLJZ6I4RPPI4MLQWZOFLANCNFSM4JUYEDXQ .

ThiNepo commented 4 years ago

I was thinking about the Swagger layout and I think that is better let as it is now. You just need to put a small example in the README of how to change it (also not a priority).

and you are right. If you take my example code above I can customize the Swagger layout just passing the template_folder as a parameter and adding the two HTML files (redoc.html and swagger.html) inside the _templateapi folder.

About the tags, my implementation was just a test, it works but it does not mean it is the right way to do. Think about how to incorporate it, maybe using a concept similar to Blueprints would be the way to go.

An official way to support tags is the only thing holding me back to start using this library hahaha.

Anyways, keep your amazing work! It can only get better from here!

PS: In the More feature example there is a small typo, you create the e233 and pass the e403.

kemingy commented 4 years ago

The "tags" implementation in FastAPI is also the same way. https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags

I guess the blueprint way may look like this:

from flaskerk import Flaskerk, Tags
from flask import Flask, jsonify

api = Flaskerk()
cat = Tags('cat')
dog = Tags('dog')
app = Flask(__name__)

@app.route('/api/ping')
@api.validate()
@cat
def ping():
    return jsonify(msg='pong')

@app.route('/api/demo')
@api.validate()
@cat
@dog
def demo():
    return jsonify(msg='demo test')

if __name__ == '__main__':
    api.add_tags(cat, dog)
    api.register(app)
    app.run()

So if there are multiple tags for one route, it may have too many decorators.

I guess just add tags to validate() function is the better way.

ThiNepo commented 4 years ago

Looks good!

I think that for an initial implementation we can just add it in the validate function. In the future, we can include something like the APIRouter implemented by FastAPI (that was what I meant when I said "similar to Blueprints").

Here is an example:

from fastapi import Depends, FastAPI, APIRouter

app = FastAPI(
    title="Some FastAPI Test",
    version="1.0.0"
)

#-------------------------------------------------

router1 = APIRouter()
@router1.get("/test")
async def test1():
    return {"msg": "Test"}

app.include_router(
    router1,
    prefix="/my-tests",
    tags=["my tests"],    
)

#--------------------------------------------------

router2 = APIRouter()
@router2.get("/test")
async def test2():
    return {"msg": "Test"}

app.include_router(
    router1,
    prefix="/other-tests",
    tags=["other tests"],    
)
kemingy commented 4 years ago

The new version (v0.6.3) now supports tags in validate().

The APIRouter can be a feature in the future.

I'll work on the enhanced layout later.

ThiNepo commented 4 years ago

Great! Thank you!

kemingy commented 4 years ago

Hi @ThiNepo , this library may be archived in the future. Since spectree supports all the features with a better interface. Feel free give it a try!

ThiNepo commented 4 years ago

Thanks for letting me know. I will take a look at spectree!