Asynchronous Random User Information Fetching

  • Share this:

Code introduction


This code defines an asynchronous function that uses the aiohttp library to fetch user information from a random user API and prints out the user's name, email, and phone number.


Technology Stack : aiohttp, asyncio, random

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 print_random_user_info():
    async with aiohttp.ClientSession() as session:
        user_data = await fetch_random_user(session)
        print(f"Name: {user_data['results'][0]['name']['first']} {user_data['results'][0]['name']['last']}")
        print(f"Email: {user_data['results'][0]['email']}")
        print(f"Phone: {user_data['results'][0]['phone']}")