Asynchronous Random User Fetch with aiohttp

  • Share this:

Code introduction


This code defines an asynchronous function to fetch random user information by sending a GET request to https://randomuser.me/ using the aiohttp library and parsing the returned JSON data.


Technology Stack : aiohttp, asyncio, aiohttp.ClientSession, aiohttp.ClientResponse, json

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio
import random

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

# JSON representation