Johnny John Boy
Johnny John Boy

Reputation: 3202

Python - POST Multiple Records in one API Call

I'm using Python 3 with an API to send a single JSON payload like this which works fine but slow because I have 200 items to send regularly:

{
  "first_name":"Ellen",
  "address_country":"US"
}

I've checked and I can send this payload manually and it creates two records which is what I need:

{
    ["first_name":"Ellen",
    "address_country":"US"],

    ["first_name":"John",
    "address_country":"US"]

}

But I can't seem to programatically generate the multiple records. Currently my code is:

payload = {}
payload['first_name'] = "Ellen"
payload['address_country'] = "US"
json_payload = json.dumps(payload)

How do I add a second record to the payload, I'm keep overwriting it.. I essentially want to iterate through my array building up my payload and send x number of results at once rather than each array iteration sending a single payload.

Okay so thank you to everyone who replied but it didn't fix the issue, I get a JSON payload which looks like the following which is what I think you meant:

[
    {"first_name":"Ellen",
    "address_country":"US"},

    {"first_name":"John",
    "address_country":"US"}

]

But the server throws back a error code 400 saying none of the fields are there (which they are). I assume that their API can only accept one input per request.. :-(

Upvotes: 0

Views: 3150

Answers (1)

Yam Mesicka
Yam Mesicka

Reputation: 6581

You just need to use the right signs :)

[
    {"first_name":"Ellen",
    "address_country":"US"},
    {"first_name":"John",
    "address_country":"US"}
]

To do it line by line:

import json
payload = []
current_person = {}
current_person['first_name'] = 'Ellen'
current_person['address_country'] = 'US'
payload.append(current_person)
current_person['first_name'] = 'Ronnie'
current_person['address_country'] = 'Canada'
payload.append(current_person)
json_payload = json.dumps(payload)

Or even:

persons = [('Ronnie', 'Canada'), ('Ellen', 'US')]
json_payload = []
for name, country in persons:
     json_payload.append({'name': name, 'country': country})

Upvotes: 1

Related Questions