python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.16k stars 335 forks source link

Nested jsonschema with api documentation #534

Closed gautierrog closed 1 year ago

gautierrog commented 1 year ago

I want to provide my model as jsonschema

foo_model = api.schema_model('Foo', foo_jsonschema)

@api.route('/foo')
@api.doc(model = foo_model)
class FooCtrl(Resource):
    def get():
        ...

It works fine, however, Foo has a reference to Bar model, the Bar definition is not included in the documentation, thus the documentation being incomplete.

Is there a way to provide additional definitions along with a model when using jsonschema?

peter-doggart commented 1 year ago

@gautierrog Yes, you can tell restx to include all models using the flask config field RESTX_INCLUDE_ALL_MODELS.

import flask
from flask_restx import Api, Namespace, Resource
from flask_restx import reqparse
from flask_restx import Api

# Our Flask app and API
app = flask.Flask(__name__)
api = Api(
    app,
    version="1.0.0",
    title="Tester",
    description="Test parsing arguments",
)

address = api.schema_model('Address', {
    'properties': {
        'road': {
            'type': 'string'
        },
    },
    'type': 'object'
})

person = api.schema_model('Person', {
    'required': ['address'],
    'properties': {
        'name': {
            'type': 'string'
        },
        'age': {
            'type': 'integer'
        },
        'birthdate': {
            'type': 'string',
            'format': 'date-time'
        },
        'address': {
            '$ref': '#/definitions/Address',
        }
    },
    'type': 'object'
})

class RouteWithArgs(Resource):

    @api.doc(model = person)
    def get(self):
        return "Ok", 200

# routes
api.add_resource(RouteWithArgs, "/args")

if __name__ == "__main__":
    app.config["RESTX_INCLUDE_ALL_MODELS"] = True
    app.run(debug=True)

The nested model should then also be in the docs:

image

gautierrog commented 1 year ago

Exactly what I was looking for, thank you.