Asynchronous Random User Fetch and Print

  • Share this:

Code introduction


This code defines an asynchronous function that fetches random user information from the https://randomuser.me/ API and prints the user's name, email, and phone number.


Technology Stack : Python, aiohttp, asyncio

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio

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

async def print_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']}")