API Calls

Application Programming Interface (API)

It's a "contract" that defines how separate software interacts with each other.

HTTP Requests

GET - get data (what are the available timings tomorrow)

POST - creating or inserting new data (making a lunch reservation)

PUT - update existing data (updating the timing for a lunch reservation)

DELETE - deletes data (removing your lunch reservation)

Let's Start

First, we import an external library that helps us make API calls

import requests

Next, we will query an API of your choice.

  • Google the API you are looking for (e.g. searching "random cat facts API" )

  • We will then make use of this API: https://catfact.ninja/

To obtain a random fact, we call .get on /fact

# add /fact to the end of the API url
endpoint = "https://catfact.ninja/fact"


# Sends a GET request to the endpoint
# This calls a random fact 
response = requests.get(endpoint)
response
  • When running this, you should get <Response [200]> .

  • A status code of 200 means the API call was successful.

Let's call the data we received

response.text

We should get a random fact about cats in a dictionary

# '{"fact":"Some common houseplants poisonous to cats include: English Ivy, iris, mistletoe, philodendron, and yew.","length":103}'

API responses are typically encoded as JSON (JavaScript Object Notation). For us to use it in python, we can call the .json() method to convert it into a dictionary.

response.json()
# {"fact":"Some common houseplants poisonous to cats include: English Ivy, iris, mistletoe, philodendron, and yew.","length":103}

# type: dict

Call the fact and print the String

fact = response.json()["fact"]
print(fact)
# Some common houseplants poisonous to cats include: English Ivy, iris, mistletoe, philodendron, and yew.

Piecing it all together

def get_cat_fact():
    endpoint = "https://catfact.ninja/fact"
    response = requests.get(endpoint)
    fact = response.json()["fact"]
    return fact

print(get_cat_fact())

Another Example

Finding the parking lots available at a carpark

Description of the API can be found here

endpoint = "https://api.data.gov.sg/v1/transport/carpark-availability"

response = requests.get(endpoint)

This sends a query to the API to obtain the carpark availability

# Need to figure out how to navigate the data to extract only what is necessary

carpark_data = response.json()["items"][0]["carpark_data"]
len(carpark_data)

Retreives the number number of carparks with data

for carpark_info in all_carpark_info:
    if carpark_info["carpark_number"] == "HE12":
        print(carpark_info)
        break
# pulls out the respective information of capark HE12

Last updated