2

I need to download many different users data in a very slow API, so I decided to make parallel requests. After trying multithreads and multiprocess I decided asynco download would be the best in my case, and my code works for some cases I have tried without the header that includes the Bearer Auth... But in this case it gives ClientConnectorCertificateError... Any ideas what I am doing wrong?

import aiohttp
import asyncio
import time

start_time = time.time()
headers =  {'accept': 'application/json','Authorization': "Bearer {}".format(token)}

async def get_cch(session, url):
    async with session.get(url, headers=headers) as resp:
        cch = await resp.json()
        x= cch['data']['contractId']
        return open(f'{x}.json', 'w').write(json.dumps(cch))


async def main():

    async with aiohttp.ClientSession(headers=headers) as session:

        tasks = []
        for contract in range(len(file_name_list)):
            start_date = '2018-01-01'
            end_date = '2018-01-05'
            url = 'https://apinergia.somenergia.coop/cch/'+file_name_list[contract]+'?tariff=None&type=tg_cchfact&from_='+start_date+'&to_='+end_date+'&limit=30000'
            tasks.append(asyncio.ensure_future(get_cch(session, url)))

        original_cch = await asyncio.gather(*tasks)
        for cch in original_cch:
            print(cch)

await main()

print("--- %s seconds ---" % (time.time() - start_time)) 
Ericp
  • 21
  • 1
  • 3
  • https://docs.aiohttp.org/en/stable/client_advanced.html – mama Nov 19 '21 at 11:25
  • Just add headers like in the requests library `headers = {'Authorization': 'bearer ASDasdqwp1231asd1231.asd123'}` – mama Nov 19 '21 at 11:26
  • I have done it, it is in the example code, but it gives me an error that doesnt appear in urls without headers – Ericp Nov 19 '21 at 11:38
  • @Ericp See https://stackoverflow.com/questions/68891425/clientconnectorcertificateerror - the error you're referring to is probably an additional error, and it seems like you're passing the API key well – Dean Gurvitz Jul 10 '23 at 06:25

1 Answers1

0

Passing a bearer token is done just like passing any other header in aiohttp, using the headers parameter of the request. There is no special method/syntax to do this, unlike the case of aiohttp.BasicAuth. In this case, you're doing it correctly, by adding the "Authorization": "Bearer <API_KEY>" pair to the headers dictionary.

The errors you're experiencing are most probably unrelated to how you pass the token.

Dean Gurvitz
  • 854
  • 1
  • 10
  • 24