10

Background

  • python 2.7
  • requests module
  • http post with duplicate keys to specify multiple values

Problem

Trevor is using python requests with a website that takes duplicate keys to specify multiple values. The problem is, JSON and Python dictionaries do not allow duplicate keys, so only one of the keys makes it through.

Goal

  • The goal is to use python requests to create an HTTP post with duplicate keys for duplicate names in the POST name-value pairs.

Failed attempts

## sample code
payload = {'fname': 'homer', 'lname': 'simpson'
         , 'favefood': 'raw donuts'
         , 'favefood': 'free donuts'
         , 'favefood': 'cold donuts'
         , 'favefood': 'hot donuts'
         }
rtt = requests.post("http://httpbin.org/post", data=payload)

See also

Web links:

Question

  • How can Trevor accomplish this task using python requests?
dreftymac
  • 31,404
  • 26
  • 119
  • 182

1 Answers1

16

You can composite payload in this way:

payload = [
    ('fname', 'homer'), ('lname', 'simpson'),
    ('favefood', 'raw donuts'), ('favefood', 'free donuts'),
]
rtt = requests.post("http://httpbin.org/post", data=payload)

But if your case allows, I prefer POST a JSON with all 'favefoood' in a list:

payload = {'fname': 'homer', 'lname': 'simpson', 
    'favefood': ['raw donuts', 'free donuts']
}
# 'json' param is supported from requests v2.4.2
rtt = requests.post("http://httpbin.org/post", json=payload)

Or if JSON is not preferred, combine all 'favefood' into a string (choose separator carefully):

payload = {'fname': 'homer', 'lname': 'simpson',
    'favefood': '|'.join(['raw donuts', 'free donuts']
}
rtt = requests.post("http://httpbin.org/post", data=payload)
ZZY
  • 3,689
  • 19
  • 22
  • **// Or if JSON is not preferred, combine all 'favefood' into a string (choose separator carefully): //** Have you tried this with the python requests library or do you have a reference to the source code or documentation that shows this is supported? – dreftymac Nov 25 '14 at 11:00
  • 1
    Did you ask about the JSON way or combined string way? Combine strings into a single one, and let `requests` to form-encode is the traditional way, you can see the usage example at: http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests. The "json" parameter was just added in 2.4.2 [changelog](https://pypi.python.org/pypi/requests/). Source codes also show the usage: `def post(url, data=None, json=None, **kwargs)` (https://github.com/kennethreitz/requests/blob/master/requests/api.py) – ZZY Nov 25 '14 at 14:31
  • 1
    In older `requests` library, post a JSON can be done as: http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers – ZZY Nov 25 '14 at 14:33