9

Ho do you configure the app to have following features:

  1. Have an api-endpoint defined as app.add_route('/v1/tablets', TabletsCollection())

  2. And still be able to use QueryParams like this https://example.com/api/v1/tablets?limit=12&offset=50&q=tablet name

the Collection has two methods on_get for retrieving the whole list and using the filter and on_post for the creation of a single record.

I've been searching the net for some time, how do you get query_string and properly parsed params?

gboffi
  • 22,939
  • 8
  • 54
  • 85
woss
  • 933
  • 1
  • 11
  • 20

3 Answers3

13

Both the query string and the parsed query string (as a dict) are available on the Request object that falcon passes to your API endpoint.

Your handler can do stuff like:

class TabletsCollection():
    def on_post(self, req, resp):
        print req.query_string
        for key, value in req.params.items():
            print key, value

See http://falcon.readthedocs.io/en/stable/api/request_and_response.html#Request.query_string and http://falcon.readthedocs.io/en/stable/api/request_and_response.html#Request.params.

Max Gasner
  • 1,191
  • 1
  • 12
  • 18
  • Thanks for the answer but I've tried that straight at the beginning and for some reason, it does not work. here is gist that i modified from the tutorial page https://gist.github.com/woss/db48b850503a09ac5fa092498970d1d4 – woss Oct 21 '17 at 15:44
  • do i need to specify the Content-Type to be something else than `application/json` ? – woss Oct 21 '17 at 15:45
  • I made a small change to your gist (`TabletsCollection` rather than `TabletsResource` on line 17) and ran it with `uwsgi --wsgi-file falcon-app.py --callable app --http :9000`. If I then run `curl localhost:9000/v1/tablets?foo=bar` I get the response `{"qs": "foo=bar", "params": {"foo": "bar"}}`. This works even if I set the content-type: `curl localhost:9000/v1/tablets?foo=bar -H "Accept: application/json" -H "Content-Type: application/json"`. Maybe the issue is in whatever you're using to make requests. – Max Gasner Oct 30 '17 at 19:56
  • 1
    i figured it out :) issue is explained below, and there was nothing to do with FW itself. Other colleague of mine was writing the nginx config and apparently forgot to proxy the query params to gunicorn :) – woss Nov 09 '17 at 15:56
1

You can use falcon.uri module to parse query string.

qs = falcon.uri.parse_query_string(req.query_string)
        if "myq" in qs:
            searchedQ = qs["myq"]
-2

After some time I figured it out, it issue was not with the Falcon as I thought in the beginning. The issue was in Nginx config that is proxying requests to the gunincorn.

You can find full answer here with nginx,how to forward query parameters? or short answer here:

Part of nginx config file

location ~ ^/api/(.*)$ {
    # ... your code
    # need to pass all the args to proxy
    proxy_pass http://gunicorn/$1$is_args$args;
}
woss
  • 933
  • 1
  • 11
  • 20