DEV Community

Nivesh Bansal
Nivesh Bansal

Posted on Edited on

Fetch Random User Data Using Python and Free Public API

Learn how to use the requests library in Python to fetch random user data from a public API. This is a beginner-friendly example to understand API requests, JSON parsing, and error handling.

import requests

# Function to fetch random user data from the public API
def fetch_data_with_API():
    url = "https://api.freeapi.app/api/v1/public/randomusers/user/random"

    # Sending a GET request to the API endpoint
    response = requests.get(url)

    # Parsing the JSON response
    data = response.json()

    # Checking if the response contains valid user data
    if data["data"] and "data" in data:
        user_data = data["data"]
        user_name = user_data["login"]["username"]
        user_phone = user_data["phone"]
        user_email = user_data["email"]
        user_country = user_data["location"]["country"]

        # Returning required user details
        return user_name, user_phone, user_email, user_country

    else:
        # Raising an exception if data is missing or request failed
        raise Exception("Request was not successful. Try again!")

# Main function to run the script
def main():
    try:
        # Fetching and displaying user data
        user_name, user_phone, user_email, user_country = fetch_data_with_API()
        print(f"User Name: {user_name}\nUser Phone No.: {user_phone}\nUser Email: {user_email}\nUser Country: {user_country}")
    except Exception as e:
        # Handling errors gracefully
        print(str(e))

# Entry point of the script
if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

Top comments (0)