flask-restx icon indicating copy to clipboard operation
flask-restx copied to clipboard

How to generate empty Swagger input body

Open axc450 opened this issue 4 years ago • 2 comments

I'm looking for a way to use api.doc() to document a POST request which accepts any JSON body (that is to say a valid JSON body is required, doesn't matter what is actually inside that body). At the moment, I am using a RequestParser() with a basic argument with location="json" that is passed to the api.expect(). I don't actually use this parser in my code to parse anything - it is just there to force the Swagger docs to give me a JSON body input box when clicking "Try it out".

Code example:

parser = reqparse.RequestParser()
parser.add_argument("placeholder", location="json")

class A(Resource):
  @api.expect(parser)
  def post(product):
    # Does not use parser.parse_args()
    # Only uses request.json
    ...

I understand there isn't really a way to pass custom Swagger JSON (as you would be able to pass invalid JSON) so what is the recommended approach here?

axc450 avatar Nov 07 '21 11:11 axc450

Did you find any better solution for this? I would like to do the same and what bothers me about this solution is that the field in the Swagger UI is marked as "* required". In addition, the default value of the field is something like {"placeholder": "string"} what I do not want.

Instead of the parser an empty model can be used too.

model = api.model('placeholder', {})

class A(Resource):
  @api.expect(model, validate=False)
  def post(product):

This generates the same body field with an empty JSON document but the field is still marked as "*required" an in this case it is mandatory to set validate=False to receive empty body data at all. Otherwise the request is rejected with status Bad Request.

RacOne avatar Dec 04 '21 09:12 RacOne

No, I didn't come up with anything better. I might put in a PR to add an extra argument to reqparse that generates the exact Swagger JSON we are looking for.

axc450 avatar Dec 04 '21 15:12 axc450