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}
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 toon_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With