1

I can access /v1/folder but cannot access /v1/folder/<folder-id>. Could you tell me the reason? In the flask-request document said add_resource() can route multiple URI. But I cannot. Maybe I misunderstand something. Please tell me if you find the clue.

from flask import request
from flask_restful import Resource, abort

class Folder(Resource):
  def post(self, folder_id):
      return { "message":"post with folder_id"}, 200


  def post(self):
      return { "message":"post without folder_id"}, 201



app = Flask(__name__)

.....

api_bp = Blueprint('api', __name__)
api = Api(api_bp, serve_challenge_on_401=True)
api.add_resource( Folder, '/v1/folder', '/v1/folder/<string:folder_id>')
app.register_blueprint(api_bp)

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True )

The error messages is "TypeError: post() got an unexpected keyword argument 'folder_id' ". What's wrong?

1 Answer 1

2

Python does not support function/method overloading, so the post method you declared last is always going to be the one that's used. Instead, you should use the tools Python does provide - default values for arguments.

I would personally do the following:

from flask import request
from flask_restful import Resource, abort

class Folder(Resource):
  def post(self, folder_id=None):
      if folder_id is None:
          return self.__simple_post()
      else:
          return self.__parameter_post(folder_id)

  def __parameter_post(self, folder_id):
      return { "message":"post with folder_id"}, 200

  def __simple_post(self):
      return { "message":"post without folder_id"}, 201



app = Flask(__name__)

.....

api_bp = Blueprint('api', __name__)
api = Api(api_bp, serve_challenge_on_401=True)
api.add_resource( Folder, '/v1/folder', '/v1/folder/<string:folder_id>')
app.register_blueprint(api_bp)

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True )

Or you could handle the logic in the post method, if the logic is similar enough and not too long. If the logic ends up being unreadable, though, consider using the approach I suggested.

Sign up to request clarification or add additional context in comments.

1 Comment

You are very welcome. I actually had to do this a few days ago myself, so I still remember how I handled it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.