Fetch JSON data from URL using Python

Fetch JSON data from URL using Python

Fetching JSON data from a URL in Python is a common task for interacting with web APIs. The requests library simplifies this process significantly.

For fetching JSON data from URL, you need some prerequisite to be installed in your system. These Prerequisite are as follow-

  1. Python Installed: Ensure you have Python installed. You can download it from http://python.org.
  2. Install the requests Library: If you don’t have the requests library installed, you can install it using pip:
pip install requests
  1. Import requests: Import the requests library to handle HTTP requests.
  2. Define fetch JSON Function:
    • Send a GET Request: Use requests.get(url) to send a GET request to the provided URL.
    • Check for Errors: response.raise-for_status() raises an HTTP Error if the request returned an unsuccessful status code.
    • Parse JSON: response.json() parses the JSON response into a Python dictionary or list.
    • Exception Handling: Handle potential errors such as HTTP errors, request errors, and JSON decoding errors.
  3. Define main Function:
    • Specify the URL: Set the URL of the JSON data to be fetched.
    • Call fetch_json : Fetch and print the JSON data.
  4. Run the Script: The script executes the main function if run directly.
  5. import requests
    
    def fetch_json(url):
        try:
            response = requests.get(url)
            response.raise_for_status()  # Check if the request was successful
            data = response.json()  # Parse the JSON data from the response
            return data
        except requests.exceptions.HTTPError as http_err:
            print(f"HTTP error occurred: {http_err}")
        except requests.exceptions.RequestException as req_err:
            print(f"Request error occurred: {req_err}")
        except ValueError as json_err:
            print(f"JSON decoding error: {json_err}")
    
    def main():
        url = 'https://jsonplaceholder.typicode.com/posts/1'  # Example URL
        json_data = fetch_json(url)
        
        if json_data:
            print("Fetched JSON Data:")
            print(json_data)
    
    if __name__ == "__main__":
        main()

    Output:

    For the example URL (https://jsonplaceholder.typicode.com/posts/1), the output might look like this:

  6. Fetched JSON Data:
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit... aut rerum est autem sunt rem eveniet architecto"
    }

     

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top