Asynchronous Random User Information Fetching with aiohttp

  • Share this:

Code introduction


This function uses the aiohttp library to asynchronously fetch detailed information of a random user. It first creates an asynchronous session, then sends a GET request to the random user API, and finally returns the parsed JSON response.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous HTTP request

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()

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

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