Search code examples
pythonjsonpython-3.xpolling

Polling an api in python for a specific json element


I am requesting data from an api with a json response. The json content is dynamically changing all the time. I would like my python script to continuously run and look in the json for example every 5 seconds, until a given statement is true, which could be when a given userid number is present in the json response. When the userid number is present, then make an action, for example print userid and the connected username also found in the json response.

I have been looking at the polling documentation but I can't figure out how to use it the way I want to.

I wan't to poll data['result']['page']['list'] for ['user_id'] every 5 seconds and when ['user_id'] is True then print the information connected to the user_id like the nick_name.

response = requests.post('https://website.com/api', headers=headers, data=data)

json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)

userid = input('Input userID: ')


for ps in data['result']['page']['list']:
    if userid == str(ps['user_id']):
        print('Username: ' + ps['nick_name'])
        print('UserID: ' + str(ps['user_id']))

Solution

  • What about a simple loop ?

    import time
    found_occurrence = False
    userid = input('Input userID: ')
    
    while not found_occurrence:
     response = requests.post('https://website.com/api', headers=headers, data=data)
     json_res = response.json()
     for ps in json_res['result']['page']['list']:
        if userid == str(ps['user_id']):
            print('Username: ' + ps['nick_name'])
            print('UserID: ' + str(ps['user_id']))
            found_occurrence = True
     time.sleep(5)
    

    If you want to have this run continously, you would loop infinitely (until interrupted) and log the events to a file like this:

    import logging
    import time
    import sys
    logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
    
    userid = input('Input userID: ')
    try: 
        while True:
         response = requests.post('https://website.com/api', headers=headers, data=data)
         json_res = response.json()
         for ps in json_res['result']['page']['list']:
            if userid == str(ps['user_id']):
               logging.info('Username: ' + ps['nick_name'])
               logging.info('UserID: ' + str(ps['user_id']))
         time.sleep(5)
    except KeyboardInterrupt:
      logging.info("exiting")
      sys.exit()