Efficient data retrieval in Python: Function to fetch and parse REST API responses

REST APIs have become the backbone of data exchange over the web. Python, with its simplicity and powerful libraries, is an ideal language for interacting with these APIs. This guide will walk you through how to write a Python function that makes GET requests to a REST API and parses the JSON response.

REST (Representational State Transfer) APIs are a standard way of enabling communication between different software systems. JSON (JavaScript Object Notation) is a lightweight data-interchange format often used for transmitting data in web applications.

Importing the requests library:

Start by importing the requests library:

import requests

Creating the GET request function:

Define a function that makes a GET request to a specified URL and parses the JSON response:

def fetch_api_data(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return None

Handling exceptions:

It’s important to handle potential exceptions that might occur during the request:

def fetch_api_data(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(f"Error: {e}")
        return None

Testing the function

For testing purposes, you can use a publicly available API like the JSONPlaceholder, a fake online REST API for testing and prototyping.

Example URL for testing: https://jsonplaceholder.typicode.com/todos/1

Now, call the function with this URL:

test_url = 'https://jsonplaceholder.typicode.com/todos/1'
data = fetch_api_data(test_url)
print(data)

Output

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Refer more on python here :

Author: user