Friday, October 7, 2022

The cat API

 The cat API is a public service API all about Cats. This means it is a service where people who like cats share picture and other details about cats and developers uses it in there applications.


The python code below uses the free cat api to search for random cats, fetch there details and organize it into a dataframe table and the download the pictures onto the local disc.

import json
import shutil
import requests

url = 'https://api.thecatapi.com/v1/images/search'

data_list = []
for i in range(101):
    print('Getting random cat image...', i)
    
    # Send requests...
    response = requests.get(url)
    
    # Get values from response...
    data = list(response.json()[0].values())
    
    # Append data to list...
    data_list.append(data)


# Get columns names from response...
cols = list(response.json()[0].keys())

# Create df...
data_list_df = pd.DataFrame(data_list, columns=cols)
# ===========================================



# Download images....

i = 1
for url in data_list_df['url']:
    # Get image extension...
    img_ext = url.split('.')[-1]
    imgfile_name = f'cat_{i}.{img_ext}'
    print('Processsing...', imgfile_name)
    
    # Send requests...
    res = requests.get(url, stream=True)

    # Write image to disc...
    with open(f'cat_image/{imgfile_name}','wb') as f:
        shutil.copyfileobj(res.raw, f)
        
    # Alternative: write image to disc...
    # with open(f'cat_image/{imgfile_name}','wb') as f:
    #     f.write(res.content)
    
    i = i+1
    # break


Similarly, the code above can be adapted for the Dog API or Dog CEO API.


Thank you for following.

No comments:

Post a Comment