Reputation: 39
I am pretty new to Python, only really messed with API. I am trying to get the following code to loop, and on each loop pull a new value for the "client" from a CSV file. On each line in the CSV file there is a client name, I want it to read the CSV, pull the name from line 1, loop, pull the name from line 2 and so on.. how would I go about doing this?
import json, getpass, csv, requests
from requests.auth import HTTPBasicAuth
username = input("Enter GTAX username: ")
password = getpass.getpass('Enter GTAX Password: ')
client = 'Name from line 1 - after loop line 2 and so on'
query = {'name': client}
response_API = requests.get(
'https://example.com/api/v1/clients',
auth=HTTPBasicAuth(username, password), timeout=10, params=query)
data = response_API.text
parse_json = json.loads(data)
id = parse_json['data'][0]['id']
properties = {
"qualifier": {
"value": "qualify",
"required": True,
"active": True
},
"presi": {
"value": True,
"required": True,
"active": True
},
"pool": {
"value": "VM",
"required": False,
"active": True
}
}
putproperties = requests.put(
f'https://example.com/api/v1/clients/{id}/properties/user',
auth=HTTPBasicAuth(username, password), timeout=10, verify=False, data=json.dumps(properties))
status1 = putproperties.status_code
print(status1)```
Upvotes: 0
Views: 192
Reputation: 179
Generally reading a csv is pretty straight forward. Here is my clients.csv:
client_name,client_id
John Doe,1
Max Mustermann,2
I then simply read it with csv library, line by line as a dictionary:
import csv
def do_something_with_client(name):
print(name)
with open('clients.csv') as f:
reader = csv.DictReader(f)
for line in reader:
do_something_with_client(line["client_name"])
If your CSV does not have a header, you can provide one:
reader = csv.DictReader(f, fieldnames=["client_name", "client_id"])
You can refer to the official documentation to find more examples on how to use the csv library.
Upvotes: 2