Asynchronous Random User Fetching with aiohttp

  • Share this:

Code introduction


This code defines an asynchronous function to fetch random user information from the API at https://randomuser.me/. It first creates an aiohttp client session, then sends a GET request to the API, and finally parses the returned JSON data.


Technology Stack : aiohttp, asyncio, Python

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():
    async with aiohttp.ClientSession() as session:
        user_data = await fetch_random_user(session)
        return user_data

# JSON Explanation