Random User Data Fetcher using httpx

  • Share this:

Code introduction


This function uses the httpx library to fetch user data from a randomly selected API endpoint. It first defines a list of possible endpoints, then randomly selects one. Next, it creates an httpx client instance, sends a GET request to the selected endpoint, and returns the JSON data or an error message based on the response status code.


Technology Stack : httpx

Code Type : HTTP Request

Code Difficulty : Intermediate


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

    # Define a list of possible endpoints
    endpoints = [
        "https://randomuser.me/api/",
        "https://jsonplaceholder.typicode.com/users",
        "https://api.github.com/users"
    ]

    # Randomly select an endpoint
    selected_endpoint = random.choice(endpoints)

    # Create a Client instance
    client = Client()

    # Make a GET request to the selected endpoint
    response = client.get(selected_endpoint)

    # Check if the request was successful
    if response.status_code == 200:
        # Return the JSON data
        return response.json()
    else:
        # Return an error message
        return {"error": "Failed to fetch data"}                
              
Tags: