3

Hi I am trying to read from a restful api

http://localhost:1010/productfamily?date=2015-08-28&list=abc,xyz

I am passing the values like this

url = 'http://localhost:1010/productfamily'
sdate = '2015-08-28'
plist = 'abc,xyz'
params = (('date', sdate ), ('list', plist))
requests.get(url, params)

I am not getting the wanted output. How do i pass a comma separated string in this way?

It works when i pass it like this

requests.get(url+?'date='+sdate'&lisy='plist)
user2728024
  • 1,496
  • 8
  • 23
  • 39

3 Answers3

4

The problem is with how you specified your params, and how you are passing them. Try this instead:

url = 'http://localhost:1010/productfamily'
sdate = '2015-08-28'
plist = 'abc,xyz'
params = {
  'date': sdate,
  'list': plist
 }
requests.get(url, params = params)
winwaed
  • 7,645
  • 6
  • 36
  • 81
  • 4
    This is the correct answer; if you have a Python list to start with, you can turn it into a suitable comma-separated string using: `plist = ",".join(map(str, plist))` – somewhatoff May 19 '16 at 11:43
  • @somewhatoff This will replace "," by "%2C" in the request url. – Manuel Popp May 10 '23 at 09:16
4

To pass multiple values for the same key, pass in a dict with an iterable as its value

url = 'http://localhost:1010/productfamily'
params = {'sdate': '2015-08-28'}
params['plist'] = ('abc', 'xy')
requests.get(url, params)

EDIT:

The OP did ask for a comma separated value list, and as somewhatoff points out in the comments, this code produces multiple key=value parameters. That being said, the OP also states that they are "reading" from an API and issuing GET requests, indicating that this is not a service that they are creating. While there is NO spec for how to provide multiple values, my experience is that "most" server frameworks will accept this format for multiple values, and I've not seen the CSV format required "in the wild."

Wikipedia supports this position here: https://en.wikipedia.org/wiki/Query_string#Web_forms

Also see this answer for more information about the behavior of specific web servers: https://stackoverflow.com/a/1746566/4075135

Community
  • 1
  • 1
ZachP
  • 631
  • 6
  • 11
  • 1
    This code generates a URL with multiple keys, like this: `http://www.example.org/?sdate=2015-08-28&plist=abc&plist=xy` rather than a comma separated string, which would be: `http://www.example.org/?sdate=2015-08-28&plist=abc,xy` – somewhatoff May 19 '16 at 11:06
  • 1
    My pleasure; I came across this because I have found it in the wild, and [this link](https://github.com/kennethreitz/requests/issues/794) suggests other people have had it too. – somewhatoff May 19 '16 at 16:33
0

You need to pass dictionary as params instead of tuple list.

params = {
      'date': sdate,
      'list': plist,
     }

requests.get(url, params)
hspandher
  • 15,934
  • 2
  • 32
  • 45