4

The get method on user works if the # api.add_resource(User, '/user/') line is uncommented, and the other api.add_resource is. The inverse of that is true to make the post method work.

How can I get both of these paths to work?

from flask import Flask, request
from flask.ext.restful import reqparse, abort, Api, Resource
import os
# set the project root directory as the static folder, you can set others.
app = Flask(__name__)
api = Api(app)

class User(Resource):

    def get(self, userid):
        print type(userid)
        if(userid == '1'):
            return {'id':1, 'name':'foo'}
        else:
            abort(404, message="user not found")

    def post(self):
        # should just return the json that was posted to it
        return request.get_json(force=True)

api.add_resource(User, '/user/')
# api.add_resource(User, '/user/<string:userid>')

if __name__ == "__main__":
    app.run(debug=True)
tylerj
  • 53
  • 1
  • 7

1 Answers1

11

Flask-Restful supports registering multiple URLs for a single resource. Simply provide both URLs when you register the User resource:

api.add_resource(User, '/user/', '/user/<userid>')
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 2
    What might be missing here is how "/" and "/id" are both supported in the python code. Would there be 2 functions with the same name? Would there be one function and the programmer would check the "id" against None? – Tony Ennis Jul 02 '18 at 00:05
  • 1
    In this framework, you'd check against `user_id is None` to distinguish the cases. – Sean Vieira Jul 02 '18 at 02:35
  • It may be a better convention to just make a new flask_restful class to represent the id routes... this is far more organized than using a conditional in every single restful function IMO... – jscul Jan 28 '19 at 18:34