You can download this code by clicking the button below.
This code is now available for download.
This function uses the aiohttp library to fetch user information from a random user API and print it out. The function first creates an asynchronous event loop, then creates a client session using aiohttp, sends a GET request to get the user information through the session, and finally prints the user information.
Technology Stack : aiohttp, asyncio
Code Type : Asynchronous network 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 = await fetch_random_user(session)
print(f"Name: {user['results'][0]['name']['title']} {user['results'][0]['name']['first']} {user['results'][0]['name']['last']}")
print(f"Email: {user['results'][0]['email']}")
print(f"Phone: {user['results'][0]['phone']}")
def xxx():
loop = asyncio.get_event_loop()
loop.run_until_complete(print_user_info())