Asynchronous Random User Data Fetcher

  • Share this:

Code introduction


This code defines an asynchronous function to fetch a random user's information from a random user generation API. It first creates an aiohttp ClientSession, then sends a GET request to the random user API, retrieves the JSON response, and extracts the user information from it.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous HTTP request and response processing

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio
import random

async 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:
        user_data = await fetch_random_user_data(session)
        return user_data['results'][0]

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