'Looping through multiple URLs for an API call function
I'm fairly new to python loops and need some assistance. I have a list of urls below. The numbers inside each of the URL represent a different product ID, and for each product ID(1,2,3 etc), the script runs a price update api call.
www.random.com/product/1/offer
www.random.com/product/2/offer
www.random.com/product/3/offer
I need to be able to loop through each of the URLs and perform the same task for each product id (1,2,3) - currently I have it setup as the following, but wondering how I can integrate a for loop into this. When I try with arrays + for loop it the script just executes the entire value inside the array when it calls the URL. Below is my code for a single URL.
URL = 'www.random.com/product/1/offer'
ua = UserAgent()
#print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
headers2 = {'Content-Type': 'application/json', 'charset': 'utf-8', 'Accept': 'application/json', 'Authorization': 'xxx'}
def main():
response = requests.get(URL, headers=header)
response_formatted = json.loads(response.content.decode('utf-8-sig').encode('utf-8'))
price1 = response_formatted[0]["salePrice"]
print(price1)
discount_by=0.10
new_discount_price= (price1-discount_by)
print(new_discount_price)
sku = response_formatted[0]["sku"]
So basically I would like to have 'URL' variable equal to a bunch of different URLs and loop the main call for each unique URL value.
Solution 1:[1]
Thanks to Adrian, I got it. Solution was:
def main():
listid=[1,2]
for i in listid:
idlist=i
URL=f'https://www.random.com/products/{idlist}/offers'
ua = UserAgent()
#print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
headers2 = {'Content-Type': 'application/json', 'charset': 'utf-8', 'Accept': 'application/json', 'Authorization': 'xxx'}
response = requests.get(URL, headers=header)
response_formatted = json.loads(response.content.decode('utf-8-sig').encode('utf-8'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harry |
