Created
December 3, 2022 22:16
-
-
Save ronsims2/6663c18261c55eb2827cb49746f49a9d to your computer and use it in GitHub Desktop.
Example: making API call is Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import csv | |
def get_img(b, sub=''): | |
image_url = f'https://dog.ceo/api/breed/{b}/{sub}/images/random' if sub else f'https://dog.ceo/api/breed/{b}/images/random' | |
img_resp = requests.get(image_url) | |
img_data = img_resp.json()['message'] | |
return img_data | |
def run(): | |
image_list = [] | |
dog_list_url = 'https://dog.ceo/api/breeds/list/all' | |
resp = requests.get(dog_list_url) | |
_dogs = resp.json() | |
dogs = _dogs['message'] | |
for breed in dogs: | |
breeds = dogs[breed] | |
if len(breeds): | |
for sub_breed in breeds: | |
img = get_img(breed, sub_breed) | |
image_list.append([img]) | |
print(f'{breed}-{sub_breed}') | |
else: | |
img = get_img(breed) | |
image_list.append([img]) | |
print(f'{breed}') | |
print(image_list) | |
with open('/Users/tace105/Desktop/foobar.csv', 'w') as f: | |
writer = csv.writer(f, delimiter=',') | |
writer.writerows(image_list) | |
print('Done!') | |
# Press the green button in the gutter to run the script. | |
if __name__ == '__main__': | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment