All you need to know to pull Data from an API using Python Requests

API Documentation

Authorization

filename = ####path to the name of your pickle file#######
print(filename)
filehandler = open(filename, ‘rb’)
refresh_token = pickle.load(filehandler)url = “https://login.microsoftonline.com/common/oauth2/v2.0/token" payload = “””client_id%0A=##########& redirect_uri=##################& client_secret=##################& code={}& refresh_token={}& grant_type=refresh_token”””.format(code,refresh_token)
headers = { ‘Content-Type’: “application/x-www-form-urlencoded”, ‘cache-control’: “no-cache” } response = requests.request(“POST”, url, data=payload, headers=headers)
r = response.json()
access_token = r.get(‘access_token’)
refresh_token = r.get(‘refresh_token’) with open(filename, ‘wb’) as f:
pickle.dump(refresh_token, f)

Calling the API and Cleaning and parsing the JSON

import json
import requestsurl = ‘https://graph.microsoft.com/v1.0/me/messages
$search=
"subject:###SUBJECT YOU WANT TO SEARCH FOR###”’headers = {
‘Authorization’: ‘Bearer ‘ +access_token,
‘Content-Type’: ‘application/json; charset=utf-8’
}r = requests.get(url, headers=headers)files = r.json()print(files)
emails = []
while True:
try:
url = files[‘@odata.nextLink’]
for item in range (0,len(files[‘value’])):
emails.append(files['value'][item]['Subject'],[files[‘value’] [item][‘bodyPreview’])
r = requests.get(url, headers=headers)
print(r.text)
files = r.json()
except:
break

Putting the Data Somewhere

import csv write_file =‘###LOCATION WHERE YOU WANT TO PUT THE CSV FILE###’
with open(write_file,’w’, newline = ‘’) as f:
writer = csv.writer(f, lineterminator = ‘\n’)
writer.writerows(emails)

Automate

  1. Using Crontab on an Ubuntu Server
0 1 * * * /full path to python environment/python /full path to file/example.py

--

--

--

If your Product gives great value, you will live immortal !

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Learning Semantic-UI

Careers in coding :

EVOLUTION OF WEB SERVICES — 1

A Love Letter to Debugger from a Software Engineer in Training

Get a Feel of JWT ( JSON Web Token )

How to start a QA strategy from scratch

Acer Swift 3 Thin & Light Laptop, 14" Full HD IPS, AMD Ryzen 7 4700U Octa-Core with Radeon…

Acer Swift 3 Thin & Light Laptop, 14

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akash M Dubey

Akash M Dubey

If your Product gives great value, you will live immortal !

More from Medium

Databricks Job Creation & permission management using Databricks api

Big data, Small data, No data —

the-lenses-for-executive-decision-making

Data Science is everywhere and everyday in our lives. You are one great data generator.

Top 20 metrics in AdTech