How to interact with APIs in Python | by Dan Root | Towards Data Science

APIs (Application Programming Interface) have an enormous impact on the development, software, and programming communities. Not only are APIs useful, but a good amount of them are surprisingly simple to conduct basic interactions with. Programming languages can interact with APIs and perform tasks to achieve specific outcomes. We will use Python for this purpose in this article. Python is one of my preferred languages, and has especially useful modules for interacting with APIs. If you haven’t already looked at some of my articles talking about the history, overview, basics, and IDEs associated to the Python language I will include them below.
I will include my GitHub repository for the code involved here.
medium.com
medium.com
medium.com
medium.com
If you haven’t ever worked with an API before you should learn about HTTP methods. I will only go into the basics for this article. I would also recommend Postman to learn and do basic tasks when beginning with HTTP methods. Postman is useful for several other purposes, as well.
www.postman.com
GET — HTTP Client uses GET method to retrieve data from a Server in a one-way direction to the Client.
POST — HTTP Client uses POST method to send data to a Server in a one-way direction to the Server. (Although, we use a Python method to achieve this)
This article will only cover the basics to get started with using HTTP methods with Python. We will also only be covering REST APIs. I am going to be using the JetBrains PyCharm IDE for this project.
www.jetbrains.com
So, say we want to get weather for the next day once per day and automatically get an email containing that content.
For this we will use the OpenWeatherMap API and the Google Gmail API:
openweathermap.org
developers.google.com
To start things off you are going to have to make an account with OpenWeatherMap, which means you must be eligible according to their policies. After making an account you will be brought to the home dashboard. Navigate to the API keys tab. This is the key you will need when we code out the GET request in Python. Then go to the API section of their website. Click the One Call API.
https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}
Now I import the requests module into Python. I will also need the pandas module.
import requestsimport pandas as pd
I will then use a GET request from the requests module to retrieve data about the weather I want to get information from. Using the OpenWeatherMap One Call API you can put together a query string. A query string is a piece of the URL (Uniform Resource Locator) that uses keys and values to perform a large amount of processes and functions. Everything after the ? is the query string.
response = requests.get("https://api.openweathermap.org/data/2.5/onecall?lat=42.937084&lon=-75.6107&exclude=current,minutely,hourly,alerts&appid=redacted&units=imperial").json()
I’m asking the server for daily data by using the parameter exclude= and the values current,minutely,hourly,alerts to filter my results down. I am going to use the coordinates of New York for this example, but you can use whatever latitude and longitude you choose.
I will now use the json_normalize() method from the pandas module to format our data correctly into a Pandas DataFrame. I will also use the record_path= parameter to focus in on the metadata that is important to what I need.
responseData = pd.json_normalize(response, record_path="daily")
You can figure out the metadata that you need by looking for it in the API documentation’s response data section. I will now grab the info I need by slicing our data down.
# get only tomorrows dataresponseData = responseData[1:2]# convert the precipitation to a percentageresponseData[’pop’][1] *100
Print the results. I used alt commands to get the degree symbol. ALT 248 | ALT 0176.
print(f"Tomorrow will have a low of: {responseData['temp.min'][1]}°.")print(f"Tomorrow will have a high of: {responseData['temp.max'][1]}°.")print(f"Tomorrow will have a {responseData['pop'][1]}% chance of precipitation.")msg_text = f"Tomorrow will have a low of: {responseData[’temp.min’][1]}°, a high of: {responseData[’temp.max’][1]}°, and a {responseData[’pop’][1]}% chance of precipitation."[out]Tomorrow will have a low of: 56.95°.Tomorrow will have a high of: 75.43°.Tomorrow will have a 20.0% chance of precipitation.
So, I now have my weather data in a format that I will use the Gmail API to send to myself once a day at 7:00 AM in the morning detailing the next day's weather for me. To do this we will need to conduct a few actions in your google account to allow this. Make sure you follow the guide on the Gmail API QuickStart Guide about authenticating your access and downloading your credentials.
developers.google.com
First you will need to import the proper packages
import pickleimport osimport base64import googleapiclient.discoveryfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport pickleimport osfrom google_auth_oauthlib.flow import InstalledAppFlow
Next you will need to set permissions:
# set permissionsSCOPES = ['https://www.googleapis.com/auth/gmail.send',          'https://www.googleapis.com/auth/gmail.modify']
Then I will set up the credentials:
home_dir = os.path.expanduser('~')json_path = os.path.join(home_dir, 'Downloads', 'credentials.json')flow = InstalledAppFlow.from_client_secrets_file(json_path, SCOPES)creds = flow.run_local_server(port=0)pickle_path = os.path.join(home_dir, 'gmail.pickle')with open(pickle_path, 'wb') as token:    pickle.dump(creds, token)home_dir = os.path.expanduser('~')pickle_path = os.path.join(home_dir, 'gmail.pickle')creds = pickle.load(open(pickle_path, 'rb'))
I can build the service now:
service = googleapiclient.discovery.build('gmail', 'v1', credentials=creds)
Last you need to send the message:
message = MIMEMultipart('alternative')message['Subject'] = "Tomorrow's daily weather alert"message['From'] = '<youremail@email.com>'message['To'] = '<youremail@email.com'messagePlain = msg_textmessageHtml = '<b>Weather Update!</b>'message.attach(MIMEText(messagePlain, 'plain'))message.attach(MIMEText(messageHtml, 'html'))raw = base64.urlsafe_b64encode(message.as_bytes())raw = raw.decode()body = {'raw': raw}message_first = bodymessage_full = (    service.users().messages().send(        userId="me", body=message_first).execute())print('Message sent!')
This should open your bowser asking you to log into your account and then asks for permissions and access for your application to send and modify messages on your account. If you don’t want this annoying message, then you will want to give your app permission in the Google Cloud Developer Platform.
cloud.google.com
I recommend reading the docs for this.
cloud.google.com
I will also want to automate the script with the Task Scheduler.
I start by typing task scheduler in my search bar on the task bar. This will open an application that can schedule out different programs.
Click the Action menu and select Create Basic Task... from the list.
I proceed to then fill in the basic information about the application. Select Next when finished.
Then select the trigger as Daily. Select Next.
I entered this to be the day after I am currently authoring this article. Select Next.
Leave it on Start a program and select Next.
Program/script: should be going to the python.exe file. Add arguments should be to your Python script’s path. Select Next.
I click Finished and check to see if my task is in the Task Scheduler Library.
The script should now be automated to run every day at 7:00 AM.
Python with HTTP and APIs goes much further than this, but hopefully, this will serve as a good entry point if you are interested in this type of project or topic. If you have any questions, comments, or corrections go ahead and leave them in the responses below. Thank you for reading this article and I hope it helps.