10

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?

Angus G.
  • 79
  • 1
  • 6

2 Answers2

-1

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.

Hashir Irfan
  • 315
  • 1
  • 9
  • 5
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 09 '21 at 21:57
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Abhishek Dutt Nov 12 '21 at 04:11
-2

One way I found to get documentation is to use the @api.expect(schema) decorator.

  • 4
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 10 '21 at 15:23