Add custom HTTP method in falcon?

433 Views Asked by At

As many as HTTP frameworks support using the custom method and custom HTTP status code to be used inside the codes, I wonder that is it possible to do the same thing with Falcon?

I tried:

class MyResource:
    def on_obtain(self, req, resp):
        # do some thing

and I also add it to the API routes, but when I call this API I get HTTP/1.1 400 Bad Request with this body:

{"title":"Bad request","description":"Invalid HTTP method"}

my question is that is it possible to define obtain on this resource?

2

There are 2 best solutions below

1
On BEST ANSWER

I think you need to use Custom Routers. Just an example:

class Resource:

    def on_get(self, req, resp):
        resp.body = req.method
        resp.status = falcon.HTTP_200

    def on_example(self, req, resp):
        resp.body = req.method
        resp.status = falcon.HTTP_200

class MyRouter(routing.DefaultRouter):
    # this is just demonstration that my solution works
    # I added request method into method_map
    def add_route(self, uri_template, method_map, resource):
        super().add_route(uri_template, method_map, resource)
        method_map['EXAMPLE'] = resource.on_example

    def find(self, uri, req=None):
        return super().find(uri, req)

api = falcon.API(router=MyRouter())  # just set your router
test = Resource()
api.add_route('/test', test)

Let's check:

curl -X EXAMPLE http://127.0.0.1:8000/test
EXAMPLE⏎
curl http://127.0.0.1:8000/test
GET⏎

So, all what you need is just create Router and implement add_route() / find() methods. Hope you understand what I mean.

0
On

Falcon 3 has built-in support for custom HTTP methods.

You can either

  • use the environment variable FALCON_CUSTOM_HTTP_METHODS which is a comma-delimited list of custom methods:

    export FALCON_CUSTOM_HTTP_METHODS=EXAMPLE,PURGE
    
  • or add it programmatically to the COMBINED_METHODS constant:

    import falcon.constants
    falcon.constants.COMBINED_METHODS += ['EXAMPLE', 'PURGE']