Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to add multiple on_get methods under single class resource in Falcon?

If suppose we want to implement the following end points in single class resource, Is there any way to put multiple on_get methods within single resource that would differentiate each end point ? Because it makes sense to put under single class as they are pretty much closely related.

Possible end points :

/api/{id}

/api/v1/{id}

/api/{id}/appended

/api/v1/appended/{id}

like image 548
Yugendhar Anveshra Avatar asked Oct 28 '25 17:10

Yugendhar Anveshra


1 Answers

Yes, in Falcon 2.0, the add_route method supports a suffix keyword argument which allows you to use a single resource class for multiple endpoints. Some example code:

class UserResource:

    def on_get(self, req, resp):
        resp.media = self.repository.find_all()

    def on_get_single(self, req, resp, user_id):
        resp.media = self.repository.find_user(user_id)


resource = UserResource()

api = falcon.API()
api.add_route('/users', resource)
api.add_route('/users/{user_id}', resource, suffix='single')

From the docs of falcon.API.add_route

If a suffix is provided, Falcon will map GET requests to on_get_{suffix}(), POST requests to on_post_{suffix}(), etc. In this way, multiple closely-related routes can be mapped to the same resource. For example, a single resource class can use suffixed responders to distinguish requests for a single item vs. a collection of those same items.

If you will to see another relevant example of this usage present in Falcon's documentation, read it here.

like image 56
thrau Avatar answered Oct 31 '25 11:10

thrau