Tom154ce
Tom154ce

Reputation: 35

Limit amount of entries in API request by 10

i'm trying to create a loop that calls an API and prints the 10 most recent results to the console. This is what I have currently:

def searchLoop(contract_address):
    while True:

        response = requests.get(api_url, params={
            "module": "logs",
            "action": "getLogs",
            "address": contract_address,
            "startblock": "-10000",
            "endblock": "latest",
            "apikey": api_key
        })
        transactions = response.json()["result"]
        
        print(transactions)
        time.sleep(5)

It works but i'm not sure how I can limit it so that it only shows me the first 10 full results rather than the 17 it currently shows me before I get rate-limited? Any suggestions?

Upvotes: 1

Views: 817

Answers (1)

Just doing my best
Just doing my best

Reputation: 25

Hi I would adjust your while loop to stop when the length of transactions is 10. I cant not run your code on my machine, but it will look a bit like this.

def search_loop(contract_address):
    #here I am assuming that transactions is a list of dictionaries. let me know if it is not.
    transactions = []
    while len(transactions) <= 9:
        response = requests.get(api_url, params={
            "module": "logs",
            "action": "getLogs",
            "address": contract_address,
            "startblock": "-10000",
            "endblock": "latest",
            "apikey": api_key
        })

        transactions.append(response)
        
        print(transactions)
        time.sleep(5)

I am sorry i can't test it on my machine to see if its working. Depending on the intention of the code and how long transactions could end up being each time/how fast all this happens, you could just use

my_list_of_transactions = transactions[:9]

return my_list_of_transactions 

to end the function

Upvotes: 1

Related Questions