fonske
fonske

Reputation: 9

Import multiple hosts via API into Infoblox

I'm having an issue with importing data into Infoblox in bulk in python3 The input comes from a csv file, which has 2 columns (hostname and ip). This data is used in a loop to create multiple host records at once via API call. The script works fine if I use it only for the creation of "one" record, even in a loop. Once I use the script for multiple creations then it fails.

---
import requests
import csv

with open("./ib/devices.csv","r") as f:
    csv_reader = csv.reader(f)
    for item in csv_reader:
        host = item[0]
        hostname = host+".domain.com"
        ipv4 = item[1]    # This works fine
        #payload = "{\"name\":\"testie.domain.com\",\"ipv4addrs\": [{\"ipv4addr\":\"192.168.1.1\"}]}"
        # This doesn't work
        payload = {"name": hostname,"ipv4addrs": [{"ipv4addr":ipv4}]}

        headers = {'content-type': "application/json"}
        response = requests.request("POST", url, auth=(username, password), data=payload, headers=headers, verify=False)
        print(response.text)
----

Does anyone know what the issue might be?

This is the error I receive: {'name': 'testie.domain.com', 'ipv4addrs': [{'ipv4addr': '192.168.1.1'}]} { "Error": "AdmConProtoError: JSON Decoding: No JSON object could be decoded", "code": "Client.Ibap.Proto.JSONDecoding", "text": "JSON Decoding: No JSON object could be decoded"

If any suggestions or better solution for creating multiple records at once, I'm always open for suggestions.

Upvotes: 0

Views: 390

Answers (1)

larsks
larsks

Reputation: 311238

You either need to convert your payload dictionary into JSON first...

payload_json = json.encode(payload)
headers = {"content-type": "application/json"}
response = requests.post(
    url, auth=(username, password), data=payload_json, headers=headers, verify=False
)

Or use the json parameter of requests.post:

response = requests.post(
    url, auth=(username, password), json=payload, headers=headers, verify=False

Setting the json parameter performs the JSON serialization automatically. This also sets the Content-type to application/json, so you would no longer need to set that header explicitly.

Upvotes: 0

Related Questions