2

I have a list of users in a text file that I am reading into python, [john, mary, bob, alice] I am trying to make an API call to an application to get information about the user profile in that application. I am able to make a request using python request, the request URL looks like this:

url = https://my-application.com/api/v1/users/john

I can successfully make a single API call but I want to use python to loop through my list of users. So the question is, how do I get the request URL to replace the name of each users using a loop. I was guessing to use a for loop such as:

url = https://my-application.com/api/v1/users/%s.
for i in userlist:
   return url + str[i]

This is not making much sense to me as I cannot get it working. Any help is appreciated.

Thanks

furas
  • 134,197
  • 12
  • 106
  • 148
OneFree
  • 21
  • 1
  • 2
  • `return` is used to end function at once so it will gives you url only for first element from list. You should rather use this new url directly with some function or add to new list. – furas Dec 11 '19 at 03:46
  • if you have `%s` in string then you should use `%` to put value `url % i`. See [PyFormat.info](https://pyformat.info/) – furas Dec 11 '19 at 03:48

2 Answers2

2

Assuming you are using python 3.x something like this should work:

for username in ['john', 'mary', 'bob', 'alice']:
    url = f'https://my-application.com/api/v1/users/{username}'
    print(username)

Just replace the print with your call and processing.

Paul Whipp
  • 16,028
  • 4
  • 42
  • 54
1

Elaborating on Paul's answer, using the requests package (it will greatly simplify your code):

# Importing requests package
import requests    

# Looping over users
for username in ['john', 'mary', 'bob', 'alice']:

    # Creating URL String with username
    urlString = "https://my-application.com/api/v1/users/{}".format(username)

    # New get request
    r = requests.get(urlString)

    # Do something with the response, depending on what it is
    print(r.text()) # Print Text response
    print(r.json()) # Print JSON response

The code is very similar if you are using parameters with your GET requests, or making POST requests.

Tee
  • 126
  • 6