Skip to content

Instantly share code, notes, and snippets.

@dbetchkal
Last active September 1, 2020 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbetchkal/7653f03b80237de54566e40bbc870765 to your computer and use it in GitHub Desktop.
Save dbetchkal/7653f03b80237de54566e40bbc870765 to your computer and use it in GitHub Desktop.
Xeno-Canto API example
# Use the Xeno-Canto API to gather metadata on recordings from a specific geographic area
# then load these observations into a `pandas` DataFrame object
import requests
import json
import numpy as np
import pandas as pd
import datetime as dt
# this API request uses the bounding box search feature (lat min, long min, lat max, long max)
# but you can find other types of queries here: https://www.xeno-canto.org/help/search
scope = requests.get('https://www.xeno-canto.org/api/2/recordings?query=box:47.99,-167.344,70.845,-118.125', verify=False)
# how many pages of results will this return?
# [note: try to minimize unnecessary large requests!]
num_pages = json.loads(scope.text)['numPages']
# if you get <Response [200]> you were successful
print(scope)
# return the number of pages that are going to be loaded
print("loading", num_pages, "pages of results")
if(num_pages > 15):
print("this could take a while...")
pages = []
start = dt.datetime.now()
for page in np.arange(1, num_pages+1):
page_response = requests.get('https://www.xeno-canto.org/api/2/recordings?query=box:47.99,-167.344,70.845,-118.125&page='+str(page),
verify=False)
# the API response is JSON, load it as such
recording_meta = json.loads(page_response.text)['recordings']
# create a DataFrame from the current page and append it to the list
pages.append(pd.DataFrame(recording_meta))
print("took", dt.datetime.now()-start, "to complete")
# then we concatenate the dataframes together into one final result
xc = pd.concat(pages)
xc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment