This code will grab observations from the iNaturalist API for Vashon Biodiversity Proj¶

iNaturalist API get observations api instructions: https://api.inaturalist.org/v1/docs/#!/Observations/get_observations

includes lists of parameters and descriptions

all individual observations are stored in a list called observations each observation is a json object

In [ ]:
 
In [25]:
import requests
import json

#parameters for accessing iNaturalist API
url = "https://api.inaturalist.org/v1/observations"
project_id="vashon-biodiversity-project"
params = {
    "project_id": project_id,  
    "per_page": 100,  # Max allowed per request, get 100 at a time
    "order_by": "id",
    "order": "asc"
}

# get data
# observations is list with each observation json object as an element
response = requests.get(url, params=params)
data = response.json()
observations = data["results"]
# Store the last ID
last_id = observations[-1]["id"] if observations else None

print(len(observations))

# add to observations until you run out of observations using the last id as starting point
while last_id:
    
    params["id_above"] = last_id  # Get results after this ID
    response = requests.get(url, params=params)
    data = response.json()
    
    if not data["results"]:
        break  # Stop if no more results and get out of while loop
    
    # add results to observations list
    observations.extend(data["results"])
    
    # just a printout to check progress towards 30k observations
    if len(observations)%1000==0:
        print(len(observations), sep=" ")
    
    # Update the last_id for the next request
    last_id = data["results"][-1]["id"]

print(f"Total observations: {len(observations)}")
100
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
11000
12000
13000
14000
15000
16000
17000
18000
19000
20000
21000
22000
23000
24000
25000
26000
27000
28000
29000
30000
31000
32000
Total observations: 32902
In [26]:
#save subset of observations to file
print(len(observations))
with open("observations1.js", 'w') as file:
    json.dump(observations[32801:32902], file)
32902
In [27]:
#save all observations to file
print(len(observations))
with open("observations.js", 'w') as file:
    json.dump(observations, file)
32902
In [32]:
#create an HTML version of the notebook for viewing
import os
os.system("jupyter nbconvert --to html iNaturalist.ipynb")
[NbConvertApp] Converting notebook iNaturalist.ipynb to html
[NbConvertApp] Writing 283138 bytes to iNaturalist.html
Out[32]:
0
In [ ]: