Skip to content

Using APIs with Python – Simple JSON examples | HOXFRAMEWORK

Posted in VIDEOS

Hello and welcome !

This time we are going to dig into the APIs. Specifically JSON APIs for Python and how they work.

Basically most APIs have link modification as a way to modify what output you get, so if you have a somedogapi.com/breed/labrador you are going to get a labrador dog ; BUT some APIs will allow you to change that – for example somedogapi.com/breed/dalmatian
And now you will get a dalmatian !

However we are here to explain the API use in python.
So lets get started:
CODE 1 – cat fact:
import json
import requests #or urllib

key = requests.get(“https://catfact.ninja/fact”)
key = key.text
key = json.loads(key)
print(“FACT:”)
print(key[‘fact’])

CODE 2 – dog image:
import json
import requests #or urllib
import random

for the pic apis

print(“\nGetting the picture…”)
site = requests.get(‘https://some-random-api.ml/img/dog’)
site = site.text
print(site)

we dont get the content itself, we have to load the url

site = json.loads(site)
site = site[‘link’]
resite = requests.get(site)
resite = resite.content
random_number = random.randint(1,99)

resite = str(resite)

with open(‘./dog{}.jpg’.format(random_number),’wb’) as doggopicsaver:
doggopicsaver.write(resite)

print(“Done.”)

-And there we go! Thank you so much for visiting and have a nice day 🙂