Random User Data Fetcher Using httpx

  • Share this:

Code introduction


This function uses the httpx library to fetch user data from a randomly selected URL. It first defines a list of URLs, then randomly selects one URL, sends a GET request through httpx, and handles possible HTTP errors.


Technology Stack : Python, httpx

Code Type : Function

Code Difficulty : Intermediate


                
                    
def fetch_random_user_data():
    import httpx
    import random
    from httpx import HTTPStatusError

    # List of possible user data URLs to fetch from
    user_data_urls = [
        "https://jsonplaceholder.typicode.com/users",
        "https://randomuser.me/api/?results=1",
        "https://api.github.com/users/random"
    ]

    # Randomly select a URL from the list
    selected_url = random.choice(user_data_urls)

    # Send a GET request to the selected URL
    try:
        response = httpx.get(selected_url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        user_data = response.json()
    except HTTPStatusError as http_err:
        print(f"HTTP error occurred: {http_err}")
        user_data = None
    except Exception as err:
        print(f"An error occurred: {err}")
        user_data = None

    return user_data                
              
Tags: