Asynchronous User Information Fetching with aiohttp

  • Share this:

Code introduction


This function uses the aiohttp library to asynchronously fetch user information from a random user API and prints it out.


Technology Stack : aiohttp, asyncio, aiohttp.ClientSession, get, json

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