I'm trying to create a restful web services with flask-restx and marshmallow.
I'm using marshmallow for both request and response validations.
Since flask-restx api docs does not support marshmallow schemas in swagger ui, i want to add it using doc decorator.
Controller Code:
@ns.route('/')
class Test(Resource):
@ns.doc(params={'test': 'test'})
def get(self):
_input_schema = MySchema()
errors = _input_schema.validate(request.args)
if errors:
return Response(str(errors), status=400)
other_things()
Schema Code:
class MySchema(Schema):
title = fields.Str()
id = fields.Integer()
slug = fields.Str()
I'm trying to automatically add parameters from schema to api docs like that
@ns.doc(params=MySchema.ReturnAFieldDict())
And it will give something like that
@ns.doc(params={"title":"A string", "id": "Int value with min and max", "slug":"A str"})
Is there any way to do that?
One way I found to get documentation is to use the @api.expect(schema) decorator.
You can use api.marshal_with to document responses
from flask_restx.fields import Integer, String
test_get = api.model(
"TestGet",
{
"name": String(required=True),
"age": Integer(required=True),
},
)
@api.marshal_with(schema.test_get, code=200)
def get(self):
return {"name": "test", "age": 123}
marshal_with maps the returned dictionary or object and maps the field as per the schema. Here, in this case the returned dictionary will map on test_get schema where name will be "test" and age will be 123.