Parse GET parameters

Question:

I have an REST API where the url looks like this:

class RRervice(pyrestful.rest.RestHandler):
      @get('/Indicator/{rparms}')
      def RR(self, rparms):

        print(rparms)       
        
        ...

So when this codes executes on this URL:

http://ip:3000/Indicator/thresh=.8&symbol=AAPL

The print I get what I am supposed to get:

thresh=.8&symbol=AAPL

My question is, is there an API that ensures that certain parameters must exist, and if so, what is the best way to parse them? I have seen urllib, or maybe even argparse. I guess I am looking for the right way to do this. I know I can hack it by split, but that just solves getting what was typed in the URL, not the correctness of the URL parameters.

Asked By: Ivan

||

Answers:

As you’re already receiving the exact part of the URL that corresponds to the querystring without the question mark, if you want to parse it natively (i.e. without using the framework that you’re using), you can use parse_qs from urllib.parse:

from urllib.parse import parse_qs

...

class RRervice(pyrestful.rest.RestHandler):
      @get('/Indicator/{rparms}')
      def RR(self, rparms):
            pparams = parse_qs(rparms)
            print(pparams.get("thresh"))       
            print(pparams.get("symbol"))       
        ...

In order to enforce it, you can check whether the pparams.get(param_name) is None, like so:

if(pparams.get("thresh") is None):
   "Return your error to the client somehow"
Answered By: Diego S.