Asynchronous Random URL Data Fetching with aiohttp

  • Share this:

Code introduction


This function uses the aiohttp library to asynchronously fetch data from a random URL and prints it. It first defines an inner asynchronous function fetch_random_url, which randomly selects one from the predefined URL list and fetches its data. Then it defines an external function fetch_random_data, which starts an asynchronous event loop and calls the inner function.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous function

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio
import random

async def fetch_random_url(session):
    urls = [
        'https://api.github.com/users',
        'https://jsonplaceholder.typicode.com/todos/1',
        'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'
    ]
    url = random.choice(urls)
    async with session.get(url) as response:
        return await response.json()

def fetch_random_data():
    async def main():
        async with aiohttp.ClientSession() as session:
            data = await fetch_random_url(session)
            print(data)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

# JSON output