dreftymac
dreftymac

Reputation: 32360

handling duplicate keys in HTTP post in order to specify multiple values

Background

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

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

Upvotes: 11

Views: 7438

Answers (1)

ZZY
ZZY

Reputation: 3937

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)

Upvotes: 17

Related Questions