Asynchronous Random User Fetching with aiohttp

  • Share this:

Code introduction


This function asynchronously fetches data from an API that provides random user information using the aiohttp library, and returns the JSON-formatted user information obtained.


Technology Stack : aiohttp, asyncio, aiohttp.ClientSession, asyncio.create_task

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio
import random

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

async def get_random_user():
    async with aiohttp.ClientSession() as session:
        user = await fetch_random_user(session)
        return user