Cool API Python Scripts

Updated 13 April 2022

Let us set our codes free into the world wide web and design codes which access real world data! This real-world data will represent the current reality of the world around us. Application Programming Interface requests is the method that allows this to occur in Python Scripts. Application Programming Interface is often shortened to API. Data from the web can tell us the exact weather situation of any place on the globe, it can be used to tell us the location of faces on an image we provide or it could tell us the number of astronauts currently floating far far out there in space. Any information freely accessible on the World Wide Web is literally within our capacity to utilise inside our Python codes. 

So, this tutorial will aid understanding on API, how to request for them and explain status codes. Furthermore, it will present two API Python script examples and the process to set them up. This first API script will inform us on how many astronauts are currently in outer space. The second API script will tell us what the weather is at a certain location and whether we need to turn our sprinklers on to keep the grass green. Overview for this tutorial can be seen below.

There are several related tutorials on our website to help you become a coding virtuoso. A great place to start would be Python Rundown and Main Windows and Python and MicroPython - Compare and Access. These will also tell you locations to download the programming language Python and places to access online Python emulators. Python is a great language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB which are micro-processors that can easily fit on the palm of your hand!

As always if you have any questions, queries or things to add please let us know your thoughts!


Overview of API

API Image Demonstrating the ProcessAPI is an acronym for Application Programming Interface and is a standard that facilitates intercommunication between two or more computer programs. API are hosted on webservers however instead of a web browser asking for a webpage (like how most interactions with the internet is done today) your program will ask for data. This data is usually returned to your program in a JSON format. JSON stands for JavaScript Object Notation and is just a lightweight data-interchange format. Therefore, to get data to our program we make a request to a web server. The webserver then replies with our desired data and a status code. Sometimes to get data an API key needs to be sent along with the request to successfully return data.

Many different Python libraries can be used to get information from API. An example of one is the Requests library which is utilised in the Astronauts in Outer Space Script below in this page. In the Weather Script further below PyOWM is the library utilised to ask and get the information from an API. The Requests and PyOWM library are Python Packages which you can find on PIPy. More information on how to install packages and this website can be found in the guide Installing Python Packages.

Now there are many different ways to call information from an API but one of the most common are | get | requests. For example, to request data to a Python script using the extra functionality gained from the request library the statement | response = requests.get('http://api_example.com/example.json') | would be used. This data can be named anything, I have just used response as the identifier for this example. Now the above API doesn't exist however this is the format they tend to take.

An excellent place to find many free APIs is the online webpage Rapid API. This has numerous API, many freely able to be accessed, which can really inspire some cool coding projects. All the APIs are also rated by the community and given statistics on how quickly they respond with the desired data.


Why Use an API?

API may seem as weird at first as a Python with a hat but it'll all be explained below. Stare long enough and it becomes normalSo instead of using API data you could instead use Static Data which you have downloaded or created yourself. Data used this way with Python would work perfectly fine however there are several cases where using API data would be better. Below are examples of when APIs are more useful than static data sets.

- When data is changing quickly and you need the data to be accurate. What planes are currently in the air or what is the location of the international space station, so much data is constantly changing. To save data sets constantly needing to be re-downloaded API can jump in and solve the problem. 
- When only a small piece of a much larger data set is desired. This saves you download a huge data set when you desire only a section
- When your taking advantage of already completed, repeated computations. Sources such Facebook, Spotify and Google already have a ton of data, which have undergone serious calculations, which you can access easily with an API request.

In cases like the ones above, an API is the right solution. Using an API will save both time and effort over doing all the computation ourselves or constantly refreshing our desired data.


Status Codes

Status codes are shorthand explanations of what happened when you requested for data and are very useful when it comes to problem solving. A technical part of the API process but so long as your wise to the lingo it is not any big deal. After requesting an API there are a number of situations that can occur and each situation has a three digit numerical status code associated with it. The web server will return status codes to your computing device every single time they receive an API request.

To see the status code of your request type this line into your code | print(response.status_code) | where the placeholder text | response | is the user-defined variable name decided by you in your script line when data from the API is requested. All the potential responses that could be printed to the Python IDLE Shell can be seen below. Also, an example of asking for the status code in script can be seen in the Astronaut in Outer Space Script.

Nioce-    200    - 
This means that everything has worked, the resource was requested and the desired data was returned successfully. It will most likely be returned to python as a JSON file. JSON file (longhand is JavaScript Object Notation format) is a lightweight method to stores simple data structures and objects in. It is primarily used for data-interchange between a web application and a server. This is because when exchanging data between a browser and a server, the data can only be text.

-    301    -
This means, after the resource was requested for, the server redirected your request to a different endpoint. This can happen when an organisation switches domain names or an endpoint name is changed. The data may or may not get returned successfully.

-    400    -
This means, after the resource was requested for, the server stated you have made a bad request. When requesting sometimes must send information to gain access to the particular data you desire. This status code appears when you do not send along the right data and in this case you would not have the data you desire.

-    401    - 
This means, after the resource was requested for, the server stated that you are not authenticated. When requesting sometimes you need to send authentication information to gain access to the particular data you desire. This status code appears when you do not send the right credentials to access an API. In this case you would not have the data you desire.

-    403    - 
This means, after the resource was requested for, the server stated you do not have the right permissions to see it. Some data online is locked meaning access to them is forbidden. In this case you would not have the data you desire.

-    404    - 
This means, after the resource was requested for, the server stated that the resource you attempted to access was not found on the server. Perhaps the data has been moved, deleted or was not there to begin with. In this case you would not have the data you desire. 


Install Request Python Package - Used in Astronaut Script

To run the following code at home and to retrieve information from other API you can find online for your own coding adventures we need to expand the functionality of default Python. We can do this by installing the Request Python Package. More information on how to install packages and this website can be found in the guide Installing Python PackagesTo install the latest version of Request Python Package you would type directly into the Command Prompt the below.

pip install requests

By pressing the enter key you will execute this line. Seen below is the process that occurs in the Command Prompt once you have done this. An easy install that took less than a minute. Request comes from the Python Package Index found in this locationYou can also see recommendations to me in yellow to update the pip version to the most recent.

Pip installing the request Python Package


Astronauts in Outer Space Script

Seen below is a script that will answer the question of how many astronauts are in outer space and will also name them all. It knows this information by sending out a request for that data to a API. It has been extensively commented so that you can follow step by step. You can either type out the code in your Python Programming Window, copy and paste it or download the code from the bottom section and open it using the Python IDLE Shell.  This script references Open Notify API which is a completely free and open source project to provide a simple programming interface for some of NASA’s awesome data.

#This API returns the current number of people in space and their names and requires
#no inputs to operate.

#start by importing requests (this is what we installed before using the pip installer)

import requests

#Now we can use the functionality gained from the requests
#Below we will use the function requests.get() and the URL of the
#Open Notify API

Astronauts = requests.get('http://api.open-notify.org/astros.json')

#And just like that we now have all the information desired. Below allow you
#to print exactly the data returned by Open Notify API to the Python IDLE Shell #You will notice the data is messy and not easily legible. Uncommmenting always done by deleting # symbol. print('Below is the raw data pulled from the OpenNotifyAPI: \n') print(Astronauts.text) print(' ') #If your curious about status codes below prints to the IDLE Shell the data from API. The \n makes a paragraph break print('The status code for this API request is', Astronauts.status_code, "\n") #This data comes out not looking pretty. So, let us first make the data more readable for Python. #This means we can modify it. The function .json() will be the method to do this. #Requests Package has a built in json decode method, that can turn the API data into a native #Python datatype making it easier for Python to understand. #Below turns the API Data sent into a Python dictionary with key value pairs. Astronauts_datafix = Astronauts.json() #Below to print to IDLE Shell the Astronauts_datafix value so you can see it. Comparing it to the original data from #OpenNotifyAPI it appears nothing has changed with the data. #Below demonstrates when printed to the IDLE Shell that the data type has changed to a dictionary value. #This is good for Python to read the data. print('Below is the modified data pulled from the OpenNotifyAPI (looks the same as above but different type: \n') print(Astronauts_datafix) print(' ') print('Original API data is a', type(Astronauts)) print('Modified API data is a', type(Astronauts_datafix)) print(' ') #Now let me demonstrate just the values we desire being printed to IDLE, this being the #number of astronauts in space and a list of the people in space. This is easy to do #because we changed the API data to a dictionary type. print("The number of people in outer space is", Astronauts_datafix['number'], '! \n') print('Below are the names of the current space people:') #Below is a small loop which goes through all the people in the altered API data #and prints their name to the Python IDLE Shell for i in Astronauts_datafix["people"]: print (i["name"])

 
When this script was created there was three astronauts in outer space. What this script prints out can be see below in the Python IDLE Shell (further below is a more in-detail print out to help explain all the steps from above). As the number of astronauts change the output of the Python script will change as well. This is because the API data is constantly updated to display the most correct information. This demonstrates how you can make reliable and long-lasting code as it will always utilise the most up to date information.

Astronauts amount in space and names returned to Python IDLE Shell.

 

More expansive print out to help aid understanding can be seen below. 

Extra details returned to Python IDLE Shell. When certain sections are un-commented in code


Install PyOWM Python Package and Set up Open Weather Map API Key

There is numerous API online that are free to use so long as you create an account with their system. This is to stop their system being overloaded or made vulnerable. Thus, when we request information from API set up in this manner we need to provide some kind of input, most commonly an API key. In this case we will utilise OpenWeatherMap API for the following script. OpenWeatherMap API can be found at this location. This API will give us live information on the weather anywhere on the globe. To recreate this script you will need to make your own free account on this website. Once you have made an account and confirmed your email address you will be given an API key. The API key given to me you can see in the below screen capture. (There is no reason why you could save effort and use this key but by the time you have typed it out you may as well have made an account so you can easily copy and paste the values).

OpenWeatherMap Website Screen grab. This shows the API Key given to me after making an account

 

Also, for the next script we will install another Python Package from PyPI called PyOWM. This is a Python Wrapper Library for OpenWeatherMap web APIs. It will give more functionality to Python particularly allowing for quick and easy consumption of OpenWeatherMap API data in a human-friendly fashion. To install the latest version of PyOWM Python Package you would type directly into the Command Prompt the below.

pip install pyowm

By pressing the enter key you will execute this line. Below you can see the installation of the Python Package PyOWM in the Command Prompt (once again it is recommending an update of the pip installer). An easy install that took less than a minute. PyOWM comes from the Python Package Index found in this location. Once this is done we are ready to get into our next code! 

Installation of PyOWM occurring in the Command Prompt


Weather Script Reminding You to Turn On/Off Sprinklers

Now we have all the preparation sorted let's get into whipping up the Python script. Seen below is a Python script which depending on whether it has rained recently will turn on or off the sprinkler system.  It has been extensively commented so that you can follow step by step. You can either type out the code in your Python Programming Window, copy and paste it there or download the code from the bottom section and open it using the Python IDLE Shell.  

#Imagine that this script is run every morning, informing you what the weather will be
#and telling you whether you need to turn the sprinklers on or off. A future
#step would be to turn the sprinklers on or off automatically.

#Start by importing PyOWM (this is what we installed before using the pip installer).
import pyowm

#Now we can use the functionality gained from PyOWM in our code.

#To access the OpenWeatherMapAPI we must have a API Key which is sent
#with our request to use data from OpenWeatherMap
#This is done by using the function owm=pyowm.OWM() and our unique APIkey.
owm = pyowm.OWM('a0c664323ffe4b57a627f7585eea0748')

#Now we can decide the location of the weather data we desire. You can also use
#latitude and longitude to decide location. The world is your oyster.
city = 'Glasgow'

#Now we utilise the functionality provided by PyOWM to get the weather at our
#desired location
loc = owm.weather_manager().weather_at_place(city)

#Below is an example of using latitude and longitude to get weather data from
#OpenWeatherMap API. Uncomment below and comment above to make this run.
#use the latitude and longitude values of your choice.
#loc = owm.weather_manager().weather_at_coords(34, 150)

#Below gives a variable name to the data we have pulled from OpenWeatherAPI
weather = loc.weather

#To see the raw data that you have pulled from the API uncomment the two lines below
#print(weather)

#Below is taking the data we desire from the OpenWeatherAPI and grabbing only what we desire
temp = weather.temperature(unit='celsius')
status = weather.detailed_status

#Cleaning up the tenp data is done below so we have just the average value
cleaned_temp_data = (int(temp['temp']))

#Print the weather details to Python IDLE shell in a human readable manner
print('The temperature today in', city,'is',cleaned_temp_data,'degrees celsius.')
print('The day today will have',status,'.')

#Now to decide whether to inform the human to turn sprinklers on or off.

#The Status variable is a class string variable. Uncomment what is below to demonstrates
#this. Thus means we can search it looking for the string 'rain' inside of it.
#print(type(status)) 

#Using an if statement we can decide whether to sprinkler or not to sprinkler.
#This is done by searching for rain in status or anything rain-esque.

if 'rain' in status or 'thunderstorm' in status or 'drizzle' in status or 'snow' in status:

    print('No need for sprinklers today. Time to turn them off.')
    
else:
    
    print('Sprinklers are needed today. Time to turn them on.')

#In a future video I'll dive into the specifics of automating real life sprinklers from Python code. 

 
What this script prints out can be see below in the Python IDLE Shell. The code was run twice from the Python Programming Window with the only difference between the two altering the target city. The first time the code was run the location was set to Newcastle Australia (the location of Core Electronics). Thankfully today is a nice sunny day so sprinklers were necessary to keep our grass green. The second time running the code the city was changed to Glasgow in Scotland. Thus, the program received the weather information for Glasgow. Naturally, it was raining so sprinklers were not necessary. The correct sprinkler reminders were accurately printed to the Python IDLE Shell as well as a message about the local temperature and status of weather.

Newcastle and Glasgow Weather and whether sprinklers are needed or not


THE NEXT STEP

There is one more island to sail to before we call this Python odyssey fin. This next step would be creating graphical user interfaces (GUI). GUI is a visual way to interact with a computer using items such as windows, icons and menus. GUI with Tkinter in Python is an excellent tutorial to get you up to speed so let us dock there before we steer our ship back to the homeland. 


DOWNLOAD THE CODES

Below you can find all the code for the above examples. You will be able to run the codes here on your own computing device and modify the code at your leisure. Open the scripts with Python IDLE Shell and run them using the Python Programming Window.

Attachment - API-Python-Scripts.zip

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.