Search code examples
pythonpostgetflask-restful

Flask add resource endpoint for GET method only


How do i make Resource to pass subdomain as an argument only when GET method is triggered?

localhost:5009/my_url/9952 where get method should do some stuff based on id (9952 in this case) and localhost:5009/my_url where post does not require any id but it accepts json instead. Currently i have the following code

app = Flask(name)
app.url_map.strict_slashes = False
api = Api(app)
api.add_resource(MyResourceClass, '/my_url/<int:item_id>', endpoint='item_id')

view.py

class MyResourceClass(Resource):

    def get(self, item_id=None):
        if not item_id:
            # item ID was not provided over get method
            return 404
        # Do stuff
        return 200

    def post(self):
        ## Should accept JSON
        ## Does some stuff based on request

    def delete(self):
        ## Deletes the item information
        return 200

obviously it requires item_id to present in the URL otherwise post request returns 404 error. How do i make item_id to be required only for GET method ?


Solution

  • I figured it out

    app = Flask(name)
    app.url_map.strict_slashes = False
    api = Api(app)
    api.add_resource(MyResourceClass, '/my_url/', '/my_url/<int:item_id>', endpoint='item_id')
    

    now GET and POST will trigger regardless of item_id definition in the URL, All methods in view.py must be adjusted to handle the case where item_id is not provided