Asynchronous User Agent Fetch Using Aiohttp

  • Share this:

Code introduction


This function makes an asynchronous HTTP request using the Aiohttp library to fetch a random user agent string and returns it.


Technology Stack : Aiohttp, aiohttp.ClientSession, aiohttp.ClientRequest, json

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
def random_user_agent():
    import aiohttp
    import random
    import json

    async def fetch_random_user_agent(session):
        async with session.get('https://www.useragentstring.com/json.php') as response:
            return await response.json()

    async def main():
        async with aiohttp.ClientSession() as session:
            user_agent_data = await fetch_random_user_agent(session)
            return user_agent_data['user_agent']

    return await main()