PYTHON

Fetching Data from an External API using Python Requests

Learn to quickly fetch data from a public REST API in Python using the `requests` library, demonstrating basic GET requests and JSON parsing.

import requests
import json

def fetch_public_api_data(url, params=None):
    """
    Fetches data from a given URL using Python's requests library.
    """
    try:
        response = requests.get(url, params=params)
        response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
        return None
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Connection error occurred: {conn_err}")
        return None
    except requests.exceptions.Timeout as timeout_err:
        print(f"Timeout error occurred: {timeout_err}")
        return None
    except requests.exceptions.RequestException as req_err:
        print(f"An unexpected error occurred: {req_err}")
        return None

# Example usage: Fetch a random user from the Random User Generator API
api_url = "https://randomuser.me/api/"
data = fetch_public_api_data(api_url)

if data:
    user = data['results'][0]
    print(f"Name: {user['name']['first']} {user['name']['last']}")
    print(f"Email: {user['email']}")
else:
    print("Failed to fetch data.")
How it works: This Python snippet shows how to make a GET request to an external API using the popular `requests` library. It includes robust error handling for common issues like HTTP errors, connection problems, and timeouts, and demonstrates how to parse the JSON response. This is a fundamental building block for server-side API integrations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs