How to use query string in Falcon python
Asked Answered
I

3

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?

Insanity answered 19/10, 2017 at 14:14 Comment(0)
C
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.

Corncrib answered 19/10, 2017 at 22:32 Comment(4)
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 gist.github.com/woss/db48b850503a09ac5fa092498970d1d4Insanity
do i need to specify the Content-Type to be something else than application/json ?Insanity
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.Corncrib
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 :)Insanity
C
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"]
Cockneyfy answered 22/12, 2019 at 6:57 Comment(0)
I
-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;
}
Insanity answered 26/10, 2017 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.