Plotly REST API via Python
Let’s perform some operations on the files we have stored in our Plotly repository.
import json
import requests
from requests.auth import HTTPBasicAuth
import pandas as pd
Let’s now setup the authentication so that the Plotly web api can identify us.
username = 'your username' #however in this example the account will be 'yankev'
api_key = 'fill in with your own'
auth = HTTPBasicAuth(username, api_key)
headers = {'Plotly-Client-Platform': 'python'}
page_size = 500
Perhaps now we would like to see a list of all the folders that are present in our Plotly repository. So below we’ve written a function that takes in an argument called file
which takes either the value plot
or fold
in order to perform this task.
def get_files(file):
'''
This function will the name, fid, and path of all the files in your
plotly repository with the file type you choose
-----
Arguments
file: the type of file we want to retrieve and takes on values ['plot','fold']
Returns: A list of lists, containing the information required
'''
url = 'https://api.plot.ly/v2/folders/all?user='+username+'&filetype='+file+'&page_size='+str(page_size)
response = requests.get(url, auth=auth, headers=headers)
page = json.loads(response.content)
temp = []
for i in range(page['children']['count']):
path = requests.get('https://api.plot.ly/v2/files/{}/path'.format(page['children']['results'][i]['fid']), auth=auth, headers=headers)
#print('Filename: {}, fid: {}, path: {}'.format(page['children']['results'][i]['filename'],page['children']['results'][i]['fid'],str.split(path.content,":")[1][1:-2]))
temp.append([page['children']['results'][i]['filename'],page['children']['results'][i]['fid'],str.split(path.content,":")[1][1:-2]])
return temp
folders = get_files('fold')
We can now turn this information into a pandas data frame(just because). We write a function called files2df
in order to do this, and the argument data
will refer to the output of the get_files
function call.
def files2df(data):
'''
This function will turn your data into a dataframe
-----
Arguments
data: Output of get_files call
Returns: a data frame containing information in "data"
'''
return pd.DataFrame(data,columns=['name','fid','path'])
files2df(folders) # can also just call folders2df(get_folders())
name | fid | path | |
---|---|---|---|
0 | r-docs | yankev:0 | /r-docs |
1 | dashboard | yankev:5 | /dashboard |
2 | r-test | yankev:12 | /r-test |
Now let’s move our attention towards plots, which may be of more interest to you. So below we will retrive a list of all the plots, and simultaneously turn them into a dataframe.
plots_df = files2df(get_files('plot'))
plots_df
name | fid | path | |
---|---|---|---|
0 | usamap | yankev:1 | /r-docs/usamap |
1 | nycflights | yankev:3 | /r-docs/nycflights |
2 | earnings | yankev:6 | /dashboard/earnings |
3 | growth | yankev:8 | /dashboard/growth |
4 | performance | yankev:10 | /dashboard/performance |
5 | SFzoo | yankev:13 | /r-test/SFzoo |
6 | new_1 | yankev:19 | /dashboard/new_1 |
7 | LAzoo (1) | yankev:21 | /r-test/LAzoo (1) |
8 | chart | yankev:24 | /chart |
9 | SFzoo (1) | yankev:40 | /r-test/SFzoo (1) |
10 | SFzoo (2) | yankev:41 | /r-test/SFzoo (2) |
So it appears that we might have some extra plots with the name SFzoo. So let’s create a new folder in r-test called backups
, and then move plots 13 and 40 into it assuming that 41 is the newest rendition.
response = requests.post('https://api.plot.ly/v2/folders', data={"path": "/r-test/backups"}, headers=headers, auth=auth)
response.raise_for_status()
#Check for the new list of folders
files2df(get_files('fold'))
name | fid | path | |
---|---|---|---|
0 | r-docs | yankev:0 | /r-docs |
1 | dashboard | yankev:5 | /dashboard |
2 | r-test | yankev:12 | /r-test |
3 | backups | yankev:39 | /r-test/backups |
response = requests.patch('https://api.plot.ly/v2/files/yankev:13', data={"parent": 39}, auth=auth, headers=headers)
response.raise_for_status()
response = requests.patch('https://api.plot.ly/v2/files/yankev:40', data={"parent": 39}, auth=auth, headers=headers)
response.raise_for_status
files2df(get_files('plot'))
name | fid | path | |
---|---|---|---|
0 | usamap | yankev:1 | /r-docs/usamap |
1 | nycflights | yankev:3 | /r-docs/nycflights |
2 | earnings | yankev:6 | /dashboard/earnings |
3 | growth | yankev:8 | /dashboard/growth |
4 | performance | yankev:10 | /dashboard/performance |
5 | SFzoo | yankev:13 | /r-test/backups/SFzoo |
6 | new_1 | yankev:19 | /dashboard/new_1 |
7 | LAzoo (1) | yankev:21 | /r-test/LAzoo (1) |
8 | chart | yankev:24 | /chart |
9 | SFzoo (1) | yankev:40 | /r-test/backups/SFzoo (1) |
10 | SFzoo (2) | yankev:41 | /r-test/SFzoo (2) |
We see that we’ve successfully moved the two plots over to the newly created duplicates folder.
Assuming that we only need one backup copy of our plot, let’s throw one of these into the trash (e.g 13), and rename 40 into SFzoo_duplicate.
response = requests.patch('https://api.plot.ly/v2/files/yankev:40', data={"filename": "SFzoo_duplicate"}, auth=auth, headers=headers)
response
<Response [200]>
response = requests.post('https://api.plot.ly/v2/files/yankev:13/trash', auth=auth, headers=headers)
response
<Response [200]>
There we go, we’ve now used the REST API via Python in order to perform operations on files hosted on the Plotly servers.