Asynchronous User Info Fetching with aiohttp and asyncio

  • Share this:

Code introduction


This code defines an asynchronous function that fetches user information from a random user API and prints it to the console. It uses the aiohttp library for HTTP requests and the asyncio library to handle asynchronous tasks.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous HTTP requests and processing

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 = await fetch_random_user(session)
        print(f"Name: {user['results'][0]['name']['first']} {user['results'][0]['name']['last']}")
        print(f"Email: {user['results'][0]['email']}")
        print(f"Picture: {user['results'][0]['picture']['medium']}")

def xxx():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(print_user_info())