Asynchronous HTTP GET Request with aiohttp

  • Share this:

Code introduction


This function uses the aiohttp library to send an asynchronous HTTP GET request to the specified URL and returns the response text.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
def fetch_random_resource(url, headers=None):
    import aiohttp
    import asyncio
    async def fetch(session, url):
        async with session.get(url, headers=headers) as response:
            return await response.text()
    async def main():
        async with aiohttp.ClientSession() as session:
            return await fetch(session, url)
    loop = asyncio.get_event_loop()
    return loop.run_until_complete(main())