简体   繁体   中英

Making an API request (LinkedIn) for every element in a list from a response, with Python

I have a list of LinkedIn posts IDs. I need to request share statistics for each of those posts with another request.

The request function looks like this:

def ugcp_stats(headers):
    response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List(urn%3Ali%3AugcPost%3A{shid},urn%3Ali%3AugcPost%3A{shid2},...,urn%3Ali%3AugcPost%3A{shidx})', headers = headers)
    ugcp_stats = response.json()
    return ugcp_stats

urn%3Ali%3AugcPost%3A{shid},urn%3Ali%3AugcPost%3A{shid2},...,urn%3Ali%3AugcPost%3A{shidx} - these are the share urns. Their number depends on number of elements in my list.

What should I do next? Should I count the number of elements in my list and somehow amend the request URL to include all of them? Or maybe I should loop through the list and make a separate request for each of the elements and then append all the responses in one json file?

I'm struggling and I'm not quite sure how to write this. I don't even know how to parse the element into the request. Although I suspect it could look something like this:

for shid in shids:
    def ugcp_stats(headers):
        response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List(urn%3Ali%3AugcPost%3A & {shid})', headers = headers)
        ugcp_stats = response.json()
        return ugcp_stats

This is just a proof of what I told you earlier as comment. Now you will adapt to your needs (even I try it to do it for you) :)


link = "https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A77487&ugcPosts=List"

def ugcp_stats(headers, shids):
    # Local variable
    sample = ""
    
    # Sample the shids in the right pattern
    for shid in shids: sample += "urn%3Ali%3AugcPost%3A & {},".format(shid)
    
    # Get the execution of the string content
    response = eval(f"requests.get('{link}({sample[:-1]})', headers = {headers})")
    
    # Return the stats
    return response.json()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM