Asynchronous Random User Info Fetch Using Aiohttp and Asyncio

  • Share this:

Code introduction


This function uses the Aiohttp library and asyncio library to asynchronously obtain random user information. First, an asynchronous session is created, then the fetch_random_user_data function is called to obtain random user data, and finally, the JSON response is parsed and the information of the first user is returned.


Technology Stack : Aiohttp, asyncio

Code Type : Asynchronous function

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio
import random

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

async def get_random_user_info():
    async with aiohttp.ClientSession() as session:
        data = await fetch_random_user_data(session)
        return data['results'][0]

def xxx():
    loop = asyncio.get_event_loop()
    user_info = loop.run_until_complete(get_random_user_info())
    return user_info