You can download this code by clicking the button below.
This code is now available for download.
This function asynchronously fetches data from an API that provides random user information using the aiohttp library, and returns the JSON-formatted user information obtained.
Technology Stack : aiohttp, asyncio, aiohttp.ClientSession, asyncio.create_task
Code Type : Asynchronous HTTP request
Code Difficulty : Intermediate
import aiohttp
import asyncio
import random
def fetch_random_user(session):
async def fetch():
url = 'https://randomuser.me/api/'
async with session.get(url) as response:
return await response.json()
return asyncio.create_task(fetch())
async def get_random_user():
async with aiohttp.ClientSession() as session:
user = await fetch_random_user(session)
return user