Asynchronous Random User Fetch with aiohttp and asyncio

  • Share this:

Code introduction


This code defines an asynchronous function to fetch user information from a random user API. The function uses the aiohttp library to make network requests and the asyncio library to handle asynchronous operations.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous function

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio
import random

async def fetch_random_user(session):
    url = "https://randomuser.me/api/"
    async with session.get(url) as response:
        return await response.json()

def get_random_user_info():
    async def main():
        async with aiohttp.ClientSession() as session:
            user_info = await fetch_random_user(session)
            return user_info

    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(main())
    return result