tags:

views:

224

answers:

2

I'm building an "API API", it's basically a wrapper for a in house REST web service that the web app will be making a lot of requests to. Some of the web service calls need to be GET rather than post, but passing parameters.

Is there a "best practice" way to encode a dictionary into a query string? e.g.: ?foo=bar&bla=blah

I'm looking at the urllib2 docs, and it looks like it decides by itself wether to use POST or GET based on if you pass params or not, but maybe someone knows how to make it transform the params dictionary into a GET request.

Maybe there's a package for something like this out there? It would be great if it supported keep-alive, as the web server will be constantly requesting things from the REST service.

Ideally something that would also transform the XML into some kind of traversable python object.

Thanks!

+2  A: 

urllib.urlencode

And yes, the urllib / urllib2 division of labor is a little confusing in Python 2.x.

msw
Yes it is.. do you have any suggestions on what to use for the XML parsing? There seems to be a variety of builtin packages for xml, not sure which one is more appropriate. Lightweight wins in this case. Thx
Infinity
I've only ever used BeautifulStoneSoup for parsing XML because it just works (once you learn the model). http://www.crummy.com/software/BeautifulSoup/
msw
There is minidom, but from my limited experience I can say that lxml is a way to go
Tomasz Zielinski
+1  A: 

Is urllib.urlencode() not enough?

>>> import urllib
>>> urllib.urlencode({'foo': 'bar', 'bla': 'blah'})
foo=bar&bla=blah

EDIT:

You can also update existing url:

  >>> import urlparse, urlencode
  >>> url_dict = urlparse.parse_qs('a=b&c=d')
  >>> url_dict
  {'a': ['b'], 'c': ['d']}
  >>> url_dict['a'].append('x')
  >>> url_dict
  {'a': ['b', 'x'], 'c': ['d']}
  >>> urllib.urlencode(url_dict, True)
  'a=b&a=x&c=d'

Note that parse_qs function was in cgi package before Python 2.6

Tomasz Zielinski
I was hoping there would be something that is smart and knows how to add variables to a URL with already some query string params. e.g. given a url like `example.com?foo=bar`, if you do the string appending yourself, you have to worry about not duplicating the question mark and all that. But I guess that's left as an exercise to the developer
Infinity
Not neccesarily, take a look at my updated post
Tomasz Zielinski