Ghostwriter
Ghostwriter

Reputation: 2521

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?

Upvotes: 2

Views: 2654

Answers (2)

Gabriel Ramon
Gabriel Ramon

Reputation: 1

You can easily create dropdown lists for your API parameters in Swagger UI using the enum keyword within your @ns.param decorators. Here's how:

from flask_restx import Namespace, Resource, reqparse

ns = Namespace('EndpointName', description='...')

@ns.route('/')
@ns.param('param_1', 'param1', _in='query', type=str, enum=['option1', 'option2', 'option3'])
@ns.param('param_2', 'param2', _in='query', type=str, enum=['value1', 'value2'])
@ns.param('param_3', 'param3', _in='query', type=int, enum=[1, 2, 3])
class EndpointName(Resource):
    def post(self):
        # ... rest of your code ...

The enum keyword specifies the allowed values for each parameter, which Swagger UI will then display as a dropdown list.

You can also set a default value using the default keyword in @ns.param. This value will be pre-selected in the dropdown.

Upvotes: 0

waynetech
waynetech

Reputation: 779

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()
...

Upvotes: 4

Related Questions