pythondrop-down-menuswaggerflask-restx

Dropdown menu in Swagger with Flask (restx)


I am building my first API with the flask-restx lib. I use it to generate a Swagger documentation of my API with annotations. I currently have some fields for a post method but they all accept input as strings by default and you have to type their values in Swagger ‘Try it out’. How do I make them dropdown lists so that a user chooses an input parameter from it?

I currently use the following decorators for my namespace:

@ns.route('/')
@ns.param('param_1', 'param1')
@ns.param('param_2', 'param2')
@ns.param('param_3', 'param3')
class EndpointName(Resource):

And I parse them in a post method like this:

parser = reqparse.RequestParser()  # initialize
parser.add_argument('param_1', type=str, required=True)
parser.add_argument('param_2', type=str, required=True)
parser.add_argument('param_3', type=int, required=True)

args = parser.parse_args()

They are currently presented in swagger as input fields. How would I go about making them dropdowns with specific values to choose from? Should I add something to decorators are set types in the parser differently?


Solution

  • Instead of using @ns.param('param_1', 'param1'), you can use @ns.expect(parser) or @ns.expect(parser, validate=True) for enabling payload validation and give choices in parser.add_argument

    parser = reqparse.RequestParser()
    parser.add_argument('param_1', type=str, required=True, choices=("yes", "no"))
    ...
    
    
    
    @ns.route('/')
    @ns.expect(parser)
    class EndpointName(Resource):
       args = parser.parse_args()
    ...