0

I am using Flask==1.1.2 and flask-restplus==0.13.0 to create a rough and ready REST API.

I am following the official documentation on how to specify if an argument is required, however, I can still access the URLS without the parameters, and no error is thrown.

Also the generated Swagger UI does not reflect that the methods require parameters. How do I enforce this?

Here is my code:

from flask import Flask
from flask_restplus import Api, Resource, reqparse
from werkzeug.exceptions import BadRequest


#e = BadRequest('My custom message')
#e.data = {'custom': 'value'}
#raise e

flask_app = Flask(__name__)
app = Api(app = flask_app)


mylist_namespace = app.namespace('mylist', description='MyList API')



@mylist_namespace.route("/")
class MyListClass(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('rate', type=int, required=True,  help='Rate cannot be converted')
        parser.add_argument('name', type=str, help='Enter a name')      
        return {
            "status": "Got my list"
        }

    def post(self):
        return {
            "status": "Posted my list"
    }
Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341

1 Answers1

0

In order to run validations, you need to force reqparser to parse the data

data = parser.parse_args()

After parsing, you can access your arguments in data dict

Moreover, I would suggest you to move your parser initialization to class level to avoid extra parser creation.

class MyListClass(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('rate', type=int, required=True,  help='Rate cannot be converted')
    parser.add_argument('name', type=str, help='Enter a name') 
    def get(self):
        ...

So, your parsing will be with 'self' keyword:

data = self.parser.parse_args()
Alveona
  • 850
  • 8
  • 17