Async User Data Fetch from RandomUser.me API

  • Share this:

Code introduction


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


Technology Stack : Aiohttp-web, Python asynchronous programming

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio

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

async def display_user_data():
    async with aiohttp.ClientSession() as session:
        user_data = await fetch_random_user_data(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']}")