Search code examples
pythonapipostparametersiterator

Adding Parameter to URL to Iterate in Python


I have a Python script that I'm working on where I would like to iterate through a list of ID values at the end of a URL.

This is my script so far where I would like to replace the 555 portion of the url with a list of ID values such that the script would do a POST for each of them. How can I accomplish that?

#/bin/python3
import requests

url = "https://api.bleepbloop.com/v8/account/555"
headers = {"Accept": "application/json", "Authorization": "Bearer 123456"}
response = requests.request("POST", url, headers=headers)
print(response.text)

Solution

  • You can use a for loop, with the range function to create a list of ids:

    #/bin/python3
    import requests
    
    base_url = "https://example.com/api/"
    headers = {"Accept": "application/json", "Authorization": "Bearer 123456"}
    ids = [1,2,3,4] # or range(5)
    for id in ids:
        response = requests.request("POST", base_url + str(id), headers=headers)
        print(response.text)
    

    (working example: https://replit.com/@LukeStorry/67988932)