Asynchronous User Data Fetch Using aiohttp

  • Share this:

Code introduction


This function uses the aiohttp library to send an asynchronous HTTP GET request to a specified URL and returns user data in JSON format.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous HTTP request function

Code Difficulty : Intermediate


                
                    
def fetch_random_user():
    import aiohttp
    import asyncio

    async def fetch_user(session):
        async with session.get('https://jsonplaceholder.typicode.com/users/1') as response:
            return await response.json()

    async def main():
        async with aiohttp.ClientSession() as session:
            user = await fetch_user(session)
            return user

    return asyncio.run(main())