Is it possible to return all values returned from an API response and pass them into the pipeline to use later?

Viewed 232

I have written the following function. It returns data from an API. It returns every value from the API call. What I would like to do is take out print(lichess_response) and either yield or return the reponse so I can call any value when I call the function. That way I don't have to write a function for each value.

My code:

#import modules
import requests
import json
import re

#retrieve lichess games for a specific user
def get_lichess_games(username):

    api_session = requests.Session()
    api_headers = {
        'Authorization' : 'Bearer CZfaketokenBWo',
        'Accept'        : 'application/x-ndjson',
    }

    with api_session.get(f'https://lichess.org/api/games/user/{username}', headers=api_headers, stream=True) as response:
        for line in response.iter_lines():
            if not line:
                continue
            lichess_response = json.loads(line.decode('utf-8'))
            print(lichess_response)

get_lichess_games(username='overflowisaswamp')

An example of a single line returned from the API:

{'id': 'BMwE', 'rated': True, 'variant': 'standard', 'speed': 'rapid', 'perf': 'rapid', 'createdAt': 1620328262568, 'lastMoveAt': 1620328667690, 'status': 'resign', 'players': {'white': {'user': {'name': 'overflowisaswap', 'id': 'putineatspancakes5'}, 'rating': 1034, 'ratingDiff': 17}, 'black': {'user': {'name': 'uncrayon', 'id': 'uncrayon'}, 'rating': 1068, 'ratingDiff': -6}}, 'winner': 'white', 'moves': 'e4 e5 Nf3 Nc6 d4 exd4 Nxd4 Nxd4 Qxd4 Nf6 c3 Be7 Qe5 O-O b4 Nxe4 Qxe4 Re8 Be2 d5 Qe5 Bd6 Qxd5 Qe7 Qd3 g6 a3 Bf5 Qf3 Be4 Qe3 f5 O-O f4 Bc4+ Kh8 Qd4+ Be5 Qxe4 Bxc3 Nxc3 Qxe4 Nxe4 Rxe4 Bd5 Rd4 Bxb7 Rad8 Bb2', 'clock': {'initial': 600, 'increment': 0, 'totalTime': 600}}

I would like to yield or return rather than print, but I don't know how I would do that - something kind of like the following rough concept;

#import modules
import requests
import json
import re

#retrieve lichess games for a specific user
def get_lichess_games(username):

    api_session = requests.Session()
    api_headers = {
        'Authorization' : 'Bearer CZfaketokenBWo',
        'Accept'        : 'application/x-ndjson',
    }

    with api_session.get(f'https://lichess.org/api/games/user/{username}', headers=api_headers, stream=True) as response:
        for line in response.iter_lines():
            if not line:
                continue
            lichess_response = json.loads(line.decode('utf-8'))
            #return / yield whatever I need to do to get lichess_response into the pipleline

#when I just want the id
response= get_lichess_games(username='overflowisaswamp')
print(response['id'])

#when I just want the winner
response = get_lichess_games(username='overflowisaswamp')
print(response['winner'])

#when I just want the moves
response = get_lichess_games(username='overflowisaswamp')
print(response['moves'])

The overall goal is to be able to reuse my function, and get any value or values I want in specific situations. Rather than write a function for moves, a function for winner, a function for id, a function for status, etc. Thanks.

1 Answers

If all you want is to collect what you are currently writing to standard output in a single list, that's simply

def get_lichess_games(username):

    api_session = requests.Session()
    api_headers = {
        'Authorization' : 'Bearer CZfaketokenBWo',
        'Accept'        : 'application/x-ndjson',
    }
    results = []
    with api_session.get(f'https://lichess.org/api/games/user/{username}', headers=api_headers, stream=True) as response:
        for line in response.iter_lines():
            if not line:
                continue
            lichess_response = json.loads(line.decode('utf-8'))
            results.append(lichess_response)

    return results

If you would prefer a generator that yields values as the arrive, rather than waiting for all of them to arrive, use

def get_lichess_games(username):

    api_session = requests.Session()
    api_headers = {
        'Authorization' : 'Bearer CZfaketokenBWo',
        'Accept'        : 'application/x-ndjson',
    }
    with api_session.get(f'https://lichess.org/api/games/user/{username}', headers=api_headers, stream=True) as response:
        for line in response.iter_lines():
            if not line:
                continue
            lichess_response = json.loads(line.decode('utf-8'))
            yield lichess_response
Related