1

I am trying to get this to loop through each element in the variable list 'user' and to call the API request on each element. Right now, it only calls the API on the last element of the list.

I tried creating a for-loop that would go through each element of the list it didn't work. It would only show the info for the last user id in the list.

with open('config/config.json') as f:
    config = json.load(f)

API_KEY = config['API_KEY']

def users_info():

    user = ['usrid1', 'usrid2', 'usrid3', 'usrid4', 'usrid5', 'usrid6', 'usrid7']
    url = 'https://slack.com/api/users.info'
    headers = {'Accept': 'application/x-www-form-urlencoded'}
    payload = {
        'token': API_KEY,
        'user': user
    }
    r = requests.get(url, headers=headers, params=payload)

    if r.status_code == 200:
        print(r.json())

I am expecting it to print out the user info for each user id provided in the user list. How can I fix up my code to make that work?

2
  • 1
    "I tried creating a for-loop that would go through each element of the list it didn't work." This sounds like the way to go, can you post this code? Commented Sep 11, 2019 at 16:50
  • @C_Z_ I'm sorry. My for-loop was something along the lines of for users in user: print(r.json()). I'm pretty new to python and coding in general, so I wasn't too sure how to form the for-loop to work. Commented Sep 11, 2019 at 16:53

1 Answer 1

1

The slack documentation for this method seems to indicate you can only fetch one user's info per call. When you loop through your users, have you tried creating a request in the loop like:

with open('config/config.json') as f:
    config = json.load(f)

API_KEY = config['API_KEY']

def users_info():
    users = ['usrid1', 'usrid2', 'usrid3', 'usrid4', 'usrid5', 'usrid6', 'usrid7']
    url = 'https://slack.com/api/users.info'
    headers = {'Accept': 'application/x-www-form-urlencoded'}
    for user in users:
        payload = {
            'token': API_KEY,
            'user': user
        }
        r = requests.get(url, headers=headers, params=payload)
        if r.status_code == 200:
            print(r.json())

You should also consider the info here about how to improve performance when using the requests library, specifically the section on Sessions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.