Skip to Main Content






Getting Started With APIs

Question 4

Exercise 4: CRUD Operations with TheCatAPI 

Question: 

Create a Python script that interacts with TheCatAPI to perform the following tasks: 

  1. Fetch a list of breeds using a GET request. 
  2. Create a new vote for a cat image using a POST request. 
  3. Update the vote using a PUT request. 
  4. Delete the vote using a DELETE request. Include detailed comments explaining each step, including handling API responses, parsing JSON, error handling, and mentioning the API endpoints. 

 

Sample Code:

import requests
import json 

# Base URL for TheCatAPI
base_url = "https://api.thecatapi.com/v1" 

# Function to fetch a list of cat breeds using GET request
def fetch_breeds():
    # Construct the URL for fetching cat breeds
    url = f"{base_url}/breeds"
    # Make a GET request to fetch the breeds
    response = requests.get(url)
    

    # Check if the request was successful
    if response.status_code == 200:
        print("Successfully fetched the breeds.")
        # Parse and print the breeds data
        breeds = response.json()
        print("Breeds Data:", json.dumps(breeds, indent=4))
    else:
        print(f"Failed to fetch breeds. Status code: {response.status_code}") 

# Function to create a new vote for a cat image using POST request
def create_vote(image_id, value):
    # Construct the URL for creating a vote
    url = f"{base_url}/votes"
    # Data to be sent in the POST request
    data = {
        "image_id": image_id,
        "value": value
    }
    # Make a POST request to create the vote
    response = requests.post(url, json=data)
    

    # Check if the request was successful
    if response.status_code == 201:
        print("Successfully created a new vote.")
        # Parse and print the new vote data
        vote = response.json()
        print("Created Vote Data:", json.dumps(vote, indent=4))
        return vote["id"]
    else:
        print(f"Failed to create vote. Status code: {response.status_code}")
        return None 

# Function to update the vote using PUT request
def update_vote(vote_id, new_value):
    # Construct the URL for updating the vote
    url = f"{base_url}/votes/{vote_id}"
    # Data to be sent in the PUT request
    data = {
        "value": new_value
    }
    # Make a PUT request to update the vote
    response = requests.put(url, json=data)
    

    # Check if the request was successful
    if response.status_code == 200:
        print("Successfully updated the vote.")
        # Parse and print the updated vote data
        updated_vote = response.json()
        print("Updated Vote Data:", json.dumps(updated_vote, indent=4))
    else:
        print(f"Failed to update vote. Status code: {response.status_code}") 

# Function to delete the vote using DELETE request
def delete_vote(vote_id):
    # Construct the URL for deleting the vote
    url = f"{base_url}/votes/{vote_id}"
    # Make a DELETE request to delete the vote
    response = requests.delete(url)
    

    # Check if the request was successful
    if response.status_code == 200:
        print("Successfully deleted the vote.")
    else:
        print(f"Failed to delete vote. Status code: {response.status_code}") 

# Example usage
if __name__ == "__main__":
    # Fetch cat breeds
    fetch_breeds() 

    # Create a new vote for a cat image
    image_id = "asf2"
    vote_value = 1
    vote_id = create_vote(image_id, vote_value) 

    # Update the vote if it was created successfully
    if vote_id:
        new_vote_value = 0
        update_vote(vote_id, new_vote_value) 

        # Delete the vote
        delete_vote(vote_id)