### Install and Import PyiNaturalist Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/quickstart_v0.md Instructions for installing the library via pip and importing the necessary modules to begin using the API. ```bash pip install pyinaturalist ``` ```python from pyinaturalist import * ``` -------------------------------- ### Setup Development Environment Source: https://github.com/pyinat/pyinaturalist/blob/main/CONTRIBUTING.md Commands to clone the repository and synchronize the development environment dependencies using uv. ```bash git clone https://github.com/pyinat/pyinaturalist.git cd pyinaturalist uv sync --all-extras --all-groups ``` -------------------------------- ### Install and Initialize iNatClient in Python Source: https://github.com/pyinat/pyinaturalist/blob/main/README.md This snippet demonstrates how to install the pyinaturalist library using pip and then import and initialize the iNatClient. The iNatClient serves as the primary interface for making requests to the iNaturalist API. ```bash pip install pyinaturalist ``` ```python from pyinaturalist import * client = iNatClient() ``` -------------------------------- ### Install pyinaturalist Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/general.md Commands to install the pyinaturalist library using various package managers. Choose the method that best fits your environment. ```bash pip install pyinaturalist ``` ```bash conda install -c conda-forge pyinaturalist ``` ```bash pip install --pre pyinaturalist ``` -------------------------------- ### Enable Dry-run for Write Requests Only in Pyinaturalist Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/advanced.md Shows how to mock only `POST`, `PUT`, and `DELETE` requests while allowing `GET` requests to proceed normally, by setting the `DRY_RUN_WRITE_ONLY` environment variable. Examples are provided for Python, Unix shells, Windows CMD, and PowerShell. ```python import os os.environ['DRY_RUN_WRITE_ONLY'] = 'true' ``` ```bash export DRY_RUN_WRITE_ONLY=true ``` ```bat set DRY_RUN_WRITE_ONLY="true" ``` ```powershell $Env:DRY_RUN_WRITE_ONLY="true" ``` -------------------------------- ### Create and Update Observations Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/quickstart_v0.md Provides examples for creating a new observation with metadata and updating existing observations using an access token. ```python from datetime import datetime response = create_observation( taxon_id=54327, observed_on_string=datetime.now(), time_zone='Brussels', description='This is a free text comment for the observation', tag_list='wasp, Belgium', latitude=50.647143, longitude=4.360216, positional_accuracy=50, access_token=token, photos=['~/observations/wasp1.jpg', '~/observations/wasp2.jpg'], sounds=['~/observations/recording.mp3'], ) new_observation_id = response[0]['id'] update_observation( new_observation_id, access_token=token, description='updated description !', photos='~/observations/wasp_nest.jpg', sounds='~/observations/wasp_nest.mp3', ) ``` -------------------------------- ### Observation Creation and Update API Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/quickstart_v0.md Examples for authenticating, creating new observations, and updating existing observations. ```APIDOC ## Authentication ### Description Obtains an access token for authenticated API requests. ### Method POST ### Endpoint /oauth/token ### Parameters #### Request Body - **username** (str) - Required - Your iNaturalist username. - **password** (str) - Required - Your iNaturalist password. - **app_id** (str) - Required - Your iNaturalist application ID. - **app_secret** (str) - Required - Your iNaturalist application secret. ### Request Example ```python from pyinaturalist import get_access_token token = get_access_token( username='my_username', password='my_password', app_id='my_app_id', app_secret='my_app_secret' ) ``` ### Response #### Success Response (200) - **access_token** (str) - The obtained access token. #### Response Example ```json { "access_token": "your_generated_access_token" } ``` ``` ```APIDOC ## POST /observations ### Description Creates a new observation on iNaturalist. ### Method POST ### Endpoint /observations ### Parameters #### Request Body - **taxon_id** (int) - Required - The ID of the taxon for the observation. - **observed_on_string** (str) - Required - The date and time the observation was made. - **time_zone** (str) - Optional - The time zone of the observation. - **description** (str) - Optional - A free text comment for the observation. - **tag_list** (str) - Optional - A comma-separated list of tags. - **latitude** (float) - Required - The latitude of the observation location. - **longitude** (float) - Required - The longitude of the observation location. - **positional_accuracy** (int) - Optional - The GPS accuracy in meters. - **access_token** (str) - Required - Your iNaturalist access token. - **photos** (list[str]) - Optional - A list of paths to photos. - **sounds** (list[str]) - Optional - A list of paths to sounds. ### Request Example ```python from datetime import datetime response = create_observation( taxon_id=54327, # Vespa Crabro observed_on_string=datetime.now(), time_zone='Brussels', description='This is a free text comment for the observation', tag_list='wasp, Belgium', latitude=50.647143, longitude=4.360216, positional_accuracy=50, access_token='your_access_token', photos=['~/observations/wasp1.jpg', '~/observations/wasp2.jpg'], sounds=['~/observations/recording.mp3'] ) new_observation_id = response[0]['id'] ``` ### Response #### Success Response (200) - **observation_id** (int) - The ID of the newly created observation. #### Response Example ```json [ { "id": 123456789 } ] ``` ``` ```APIDOC ## PUT /observations/{id} ### Description Updates an existing observation's information, photos, or sounds. ### Method PUT ### Endpoint /observations/{id} ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the observation to update. #### Request Body - **access_token** (str) - Required - Your iNaturalist access token. - **description** (str) - Optional - Updated description for the observation. - **photos** (list[str] or str) - Optional - New or updated photo paths. - **sounds** (list[str] or str) - Optional - New or updated sound paths. ### Request Example ```python update_observation( 123456789, access_token='your_access_token', description='updated description !', photos='~/observations/wasp_nest.jpg', sounds='~/observations/wasp_nest.mp3' ) ``` ### Response #### Success Response (200) - **success** (bool) - Indicates if the update was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Install pyinaturalist via pip Source: https://context7.com/pyinat/pyinaturalist/llms.txt The standard command to install the pyinaturalist library in a Python environment. ```bash pip install pyinaturalist ``` -------------------------------- ### Manage Pre-commit Hooks Source: https://github.com/pyinat/pyinaturalist/blob/main/CONTRIBUTING.md Commands to install or uninstall pre-commit hooks using prek to ensure code quality before committing. ```bash prek run -a prek install prek uninstall ``` -------------------------------- ### Enable Global Dry-run Mode for Pyinaturalist Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/advanced.md Provides examples for enabling dry-run mode for all pyinaturalist requests by setting the `DRY_RUN_ENABLED` environment variable. This is useful for testing without affecting real data. Examples are provided for Python, Unix shells, Windows CMD, and PowerShell. ```python import os os.environ['DRY_RUN_ENABLED'] = 'true' ``` ```bash export DRY_RUN_ENABLED=true ``` ```bat set DRY_RUN_ENABLED="true" ``` ```powershell $Env:DRY_RUN_ENABLED="true" ``` -------------------------------- ### Create Observation Photo Grid with ipyplot (Python) Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Tutorial_1_Observations.ipynb Generates a grid of observation photos using the ipyplot library. It extracts thumbnail URLs for the first photo of each observation and uses the taxon's full name as labels. Requires the ipyplot library to be installed. ```python images = [obs.photos[0].thumbnail_url for obs in my_observations[:15]] labels = [obs.taxon.full_name for obs in my_observations[:15]] ipyplot.plot_images(images, labels) ``` -------------------------------- ### Configure Pyinaturalist Logging Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/advanced.md Demonstrates how to configure the standard Python logging module for pyinaturalist. It shows basic setup and how to set the logger level. Dependencies include the standard 'logging' module. ```python import logging logging.basicConfig() logging.getLogger('pyinaturalist').setLevel('INFO') ``` -------------------------------- ### Search Observations and Statistics Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/quickstart_v0.md Demonstrates how to retrieve observations, get species counts, and generate observation histograms using user-specific filters. ```python observations = get_observations(user_id='my_username') pprint(observations) counts = get_observation_species_counts(user_id='my_username', quality_grade='research') pprint(counts) histogram = get_observation_histogram(user_id='my_username') print(histogram) ``` -------------------------------- ### Enable Enhanced Pyinaturalist Logging Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/advanced.md Shows how to enable enhanced logging for pyinaturalist using the `enable_logging` function. This includes colorized output and better traceback formatting using the 'rich' library. Requires the 'rich' library to be installed. ```python from pyinaturalist import enable_logging enable_logging() ``` -------------------------------- ### Set iNaturalist Credentials via Environment Variables Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/authentication.md Provides examples for setting iNaturalist API credentials using environment variables across different operating systems and shells. This method avoids hardcoding credentials directly in the script. The variable names are prefixed with INAT_ and are uppercase versions of the keyword arguments. ```Python import os os.environ['INAT_USERNAME'] = 'my_inaturalist_username' os.environ['INAT_PASSWORD'] = 'my_inaturalist_password' os.environ['INAT_APP_ID'] = '33f27dc63bdf27f4ca6cd95df' os.environ['INAT_APP_SECRET'] = 'bbce628be722bfe283de4' ``` ```Bash export INAT_USERNAME="my_inaturalist_username" export INAT_PASSWORD="my_inaturalist_password" export INAT_APP_ID="33f27dc63bdf27f4ca6cd95df" export INAT_APP_SECRET="bbce628be722bfe283de4" ``` ```Batch set INAT_USERNAME="my_inaturalist_username" set INAT_PASSWORD="my_inaturalist_password" set INAT_APP_ID="33f27dc63bdf27f4ca6cd95df" set INAT_APP_SECRET="bbce628be722bfe283de4" ``` ```PowerShell $Env:INAT_USERNAME="my_inaturalist_username" $Env:INAT_PASSWORD="my_inaturalist_password" $Env:INAT_APP_ID="33f27dc63bdf27f4ca6cd95df" $Env:INAT_APP_SECRET="bbce628be722bfe283de4" ``` -------------------------------- ### Access and Manipulate Data Models Source: https://context7.com/pyinat/pyinaturalist/llms.txt Demonstrates accessing attributes of typed model objects like Observations, Taxa, and Users. Includes examples for building taxon trees and pretty-printing results. ```python from pyinaturalist import iNatClient, pprint, pprint_tree, make_tree client = iNatClient() # Observation model obs = client.observations(16227955) print(obs.taxon.name) # Taxon model taxon = client.taxa(48662) print(taxon.name) # Build and print taxon trees life_list = client.observations.life_list(user_id='my_username') tree = make_tree(life_list) pprint_tree(tree) # User model user = client.users(1) print(user.login) # Pretty print any model object or response pprint(obs) ``` -------------------------------- ### Get Access Token using Password Flow (Python) Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/authentication.md Shows how to obtain an access token directly using a username and password. This method is simpler for scripts or applications that have direct access to user credentials. It requires username, password, app_id, and app_secret. ```Python from pyinaturalist import get_access_token access_token = get_access_token( username='my_inaturalist_username', # Username you use to login to iNaturalist.org password='my_inaturalist_password', # Password you use to login to iNaturalist.org app_id='33f27dc63bdf27f4ca6cd95dd', # OAuth2 application ID app_secret='bbce628be722bfe2abde4', # OAuth2 application secret ) ``` -------------------------------- ### Search Observations API Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/quickstart_v0.md Examples for searching observations, including getting all your own observations, observation counts by species, and observation histograms. ```APIDOC ## GET /observations ### Description Retrieves a list of observations based on various search criteria. ### Method GET ### Endpoint /observations ### Parameters #### Query Parameters - **user_id** (str) - Required - The username to filter observations by. - **quality_grade** (str) - Optional - The quality grade of observations to retrieve (e.g., 'research', 'casual'). ### Request Example ```python from pyinaturalist import get_observations observations = get_observations(user_id='my_username') ``` ### Response #### Success Response (200) - **observations** (list) - A list of observation objects. #### Response Example ```json [ { "id": 117585709, "taxon": {"name": "Hyoscyamus", "rank": "genus"}, "observed_on": "2022-05-18", "user": {"login": "niconoe"}, "location": "Calvi, France" } ] ``` ``` ```APIDOC ## GET /observations/species_counts ### Description Retrieves counts of observations grouped by species. ### Method GET ### Endpoint /observations/species_counts ### Parameters #### Query Parameters - **user_id** (str) - Required - The username to filter observations by. - **quality_grade** (str) - Optional - The quality grade of observations to retrieve (e.g., 'research', 'casual'). ### Request Example ```python from pyinaturalist import get_observation_species_counts counts = get_observation_species_counts(user_id='my_username', quality_grade='research') ``` ### Response #### Success Response (200) - **species_counts** (list) - A list of species count objects. #### Response Example ```json [ { "id": 47934, "rank": "species", "scientific_name": "Libellula luctuosa", "common_name": "Widow Skimmer", "count": 7 } ] ``` ``` ```APIDOC ## GET /observations/histogram ### Description Retrieves a histogram of observations over a specified interval. ### Method GET ### Endpoint /observations/histogram ### Parameters #### Query Parameters - **user_id** (str) - Required - The username to filter observations by. - **interval** (str) - Optional - The interval for the histogram (default: 'month_of_year'). ### Request Example ```python from pyinaturalist import get_observation_histogram histogram = get_observation_histogram(user_id='my_username') ``` ### Response #### Success Response (200) - **histogram** (dict) - A dictionary representing the observation histogram. #### Response Example ```json { "1": 8, # January "2": 1, # February "3": 19 # March } ``` ``` -------------------------------- ### Initialize iNatClient with Authorization Code Flow Credentials Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Demonstrates initializing the iNatClient using the recommended authorization code flow with PKCE. Requires `app_id` and `use_pkce`. ```python creds = { 'auth_flow': 'authorization_code', 'app_id': '33f27dc63bdf27f4ca6cd95dd9dcd5df', 'use_pkce': True, } client = iNatClient(creds=creds) ``` -------------------------------- ### Get Monthly Observation Histogram for a Specific Year (Python) Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Tutorial_1_Observations.ipynb Retrieves a histogram of observations for a specific year, with counts aggregated by month. This requires specifying the `interval` as 'month' and providing start (`d1`) and end (`d2`) dates for the desired year. ```python from pprint import pprint # Assuming 'client' is an initialized PyInaturalist client instance and 'USERNAME' is defined histogram = client.observations.histogram( user_id=USERNAME, interval='month', d1='2020-01-01', d2='2020-12-31' ) pprint(histogram) ``` -------------------------------- ### Initialize iNatClient Source: https://context7.com/pyinat/pyinaturalist/llms.txt Demonstrates how to instantiate the high-level iNatClient with various configurations including locale, session settings, and authentication flows. ```python from pyinaturalist import iNatClient # Create a client instance client = iNatClient() # With default parameters for locale and preferred place client = iNatClient(default_params={'locale': 'en', 'preferred_place_id': 1}) # With session configuration (caching, rate-limiting, timeouts) client = iNatClient(per_minute=50, expire_after=3600, timeout=30, max_retries=3) # With authentication credentials (password flow) client = iNatClient(creds={ 'username': 'my_username', 'password': 'my_password', 'app_id': 'my_app_id', 'app_secret': 'my_app_secret', }) # With authentication credentials (authorization code flow - recommended) client = iNatClient(creds={ 'auth_flow': 'authorization_code', 'app_id': 'my_app_id', 'use_pkce': True, }) ``` -------------------------------- ### Build and Preview Documentation Source: https://github.com/pyinat/pyinaturalist/blob/main/CONTRIBUTING.md Commands to build project documentation using Sphinx and preview it in a browser or enable live reloading. ```bash uv run nox -e docs open docs/_build/html/index.html xdg-open docs/_build/html/index.html uv run nox -e livedocs ``` -------------------------------- ### Initialize iNatClient with Password Flow Credentials Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Shows how to initialize the iNatClient using the password flow, requiring username, password, app_id, and app_secret. ```python creds = { 'username': 'my_inaturalist_username', 'password': 'my_inaturalist_password', 'app_id': '33f27dc63bdf27f4ca6cd95dd9dcd5df', 'app_secret': 'bbce628be722bfe2abd5fc566ba83de4', } client = iNatClient(creds=creds) ``` -------------------------------- ### Initialize iNaturalist Client and Configuration Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Data Visualizations - Choropleth.ipynb Sets up the necessary file paths, taxon identifiers, and the iNatClient instance required for subsequent API calls. ```python import csv import json from pathlib import Path import altair as alt from vega_datasets import data as vega_data from pyinaturalist import iNatClient TAXON_NAME = 'Buteo jamaicensis' STATE_ABBREV = 'IA' taxon_slug = TAXON_NAME.replace(' ', '_').lower() SAMPLE_DATA_DIR = Path('.').parent / 'sample_data' COUNTY_CACHE_FILE = Path(f'{taxon_slug}_{STATE_ABBREV}_counties.json') COUNTY_ID_LOOKUP = SAMPLE_DATA_DIR / 'us_county_place_ids.csv' client = iNatClient() ``` -------------------------------- ### Configure Seaborn and Initialize iNatClient Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Data Visualizations - Seaborn.ipynb Sets up the environment by importing necessary libraries, defining constants for data processing, and initializing the iNatClient for API communication. ```python import json from datetime import datetime from pprint import pprint import matplotlib as mpl import numpy as np import pandas as pd import seaborn as sns from dateutil import tz from matplotlib import dates from matplotlib import pyplot as plt from pyinaturalist import iNatClient BASIC_OBS_COLUMNS = ['id', 'observed_on', 'location', 'uri', 'taxon.id', 'taxon.name', 'taxon.rank', 'taxon.preferred_common_name', 'user.login'] DATASET_FILENAME = 'midwest_monarchs.json' PLOT_COLOR = '#fa7b23' MIDWEST_STATE_IDS = [3, 20, 24, 25, 28, 32, 35, 38] sns.set_theme(style='darkgrid') client = iNatClient() ``` -------------------------------- ### Get Total Count of Observation Results Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Illustrates how to get the total count of results for an observation search without fetching any of the data, using the `.count()` method. ```python print(query.count()) ``` -------------------------------- ### Initialize iNatClient with Default Settings Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Demonstrates initializing the iNatClient with default settings for basic API interactions. This client will fetch data as JSON by default. ```python from pyinaturalist import iNatClient client = iNatClient() ``` -------------------------------- ### GET /observations/species_counts Source: https://github.com/pyinat/pyinaturalist/blob/main/README.md Retrieves observation counts grouped by species. ```APIDOC ## GET /observations/species_counts ### Description Retrieves the number of observations per species for a given user or filter. ### Method GET ### Endpoint client.observations.species_counts ### Parameters #### Query Parameters - **user_id** (string) - Optional - Filter by user. - **quality_grade** (string) - Optional - Filter by quality grade (e.g., 'research'). ### Request Example ```python counts = client.observations.species_counts(user_id='my_username', quality_grade='research') ``` ### Response #### Success Response (200) - **counts** (list) - A list of TaxonCount objects. #### Response Example ```json [ {"id": 48662, "name": "Danaus plexippus", "count": 13} ] ``` ``` -------------------------------- ### Configure Custom ClientSession Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/advanced.md Demonstrates how to instantiate a custom ClientSession to control HTTP request behavior for API calls. ```python from pyinaturalist import ClientSession session = ClientSession(...) request_function(..., session=session) ``` -------------------------------- ### Initialize iNatClient with Default Request Parameters Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Demonstrates initializing the iNatClient with default parameters like locale and preferred_place_id, which will be automatically applied to subsequent requests. ```python default_params={'locale': 'en', 'preferred_place_id': 1} client = iNatClient(default_params=default_params) ``` -------------------------------- ### Search and Manage Projects Source: https://context7.com/pyinat/pyinaturalist/llms.txt Illustrates searching for projects by criteria, retrieving project details, and adding observations to a project using authentication. ```python from pyinaturalist import iNatClient client = iNatClient() # Search for projects projects = client.projects.search( q='invasive', lat=49.27, lng=-123.08, radius=400, order_by='distance', ).all() # Get a project by ID project = client.projects(1234) # Add an observation to a project (requires authentication) client = iNatClient(creds={...}) client.projects.add_observations(project_id=24237, observation_ids=1234) ``` -------------------------------- ### GET /observations/search Source: https://github.com/pyinat/pyinaturalist/blob/main/README.md Searches for observations based on various criteria such as user_id. ```APIDOC ## GET /observations/search ### Description Searches for iNaturalist observations. Returns a list of Observation objects matching the provided criteria. ### Method GET ### Endpoint client.observations.search ### Parameters #### Query Parameters - **user_id** (string) - Optional - The username or ID of the user to filter observations by. ### Request Example ```python results = client.observations.search(user_id='my_username') ``` ### Response #### Success Response (200) - **results** (list) - A list of Observation model objects. #### Response Example ```json [ {"id": 117585709, "taxon": "Genus: Hyoscyamus", "observed_on": "2022-05-18"} ] ``` ``` -------------------------------- ### GET /controlled_terms Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Tutorial_1_Observations.ipynb Retrieves the list of controlled terms available on the iNaturalist platform. ```APIDOC ## GET /controlled_terms ### Description Retrieve the list of controlled terms used for annotating observations. ### Method GET ### Endpoint https://api.inaturalist.org/v1/controlled_terms ### Response #### Success Response (200) - **results** (array) - List of controlled terms. #### Response Example { "results": [ { "id": 1, "label": "Life Stage" } ] } ``` -------------------------------- ### GET /taxa Source: https://context7.com/pyinat/pyinaturalist/llms.txt Search for taxa information including names, ranks, and IDs. ```APIDOC ## GET /taxa ### Description Search for taxa using a query string or retrieve specific taxa by ID. ### Method GET ### Endpoint /taxa ### Parameters #### Query Parameters - **q** (string) - Optional - Search query string. - **rank** (list) - Optional - Filter by taxonomic rank (e.g., genus, family). ### Request Example get_taxa(q='vespi', rank=['genus', 'family']) ### Response #### Success Response (200) - **results** (array) - List of matching taxon objects. ``` -------------------------------- ### Initialize iNatClient with ClientSession Arguments Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Shows how to initialize the iNatClient by passing arguments directly to the underlying ClientSession for configuring caching, rate-limiting, timeouts, and retries. ```python client = iNatClient(per_minute=50, expire_after=3600, timeout=30, max_retries=3) ``` -------------------------------- ### Get Current User Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Endpoint to retrieve information about the currently authenticated user. ```APIDOC ## Get Current User ### Description Retrieves details for the currently logged-in user. ### Endpoint - `pyinaturalist.get_current_user()` ### Parameters This endpoint does not require any specific parameters beyond authentication. ``` -------------------------------- ### Authenticate with iNaturalist Source: https://github.com/pyinat/pyinaturalist/blob/main/README.md Shows how to initialize the iNatClient for authenticated requests. It demonstrates both direct credential usage and the recommended keyring approach. ```python creds = { 'username': 'my_username', 'password': 'my_password', 'app_id': 'my_app_id', 'app_secret': 'my_app_secret', } client = iNatClient(creds=creds) # Alternative using keyring client = iNatClient() client.observations.create(...) ``` -------------------------------- ### ClientSession Configuration for Rate Limiting Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Demonstrates how to configure ClientSession arguments for rate limiting, including setting requests per second and specifying a lock file path for multiprocess rate limiting. ```python ClientSession(per_second=0.5) ClientSession(lock_path='/tmp/pyinat.lock') ``` -------------------------------- ### GET /observations Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Tutorial_1_Observations.ipynb Retrieves a list of observations from iNaturalist, supporting filtering by user and pagination. ```APIDOC ## GET /observations ### Description Fetch observations based on specific criteria such as user ID or observation ID range. ### Method GET ### Endpoint https://api.inaturalist.org/v1/observations ### Parameters #### Query Parameters - **user_id** (string) - Optional - The username or ID of the user to filter observations by. - **per_page** (integer) - Optional - Number of results per page (max 200). - **order_by** (string) - Optional - Field to sort results by (e.g., id). - **order** (string) - Optional - Sort order (asc or desc). - **id_above** (integer) - Optional - Filter for observations with an ID greater than the specified value. ### Response #### Success Response (200) - **results** (array) - List of observation objects. #### Response Example { "total_results": 787, "results": [ { "id": 31029344, "user": "jkcook" } ] } ``` -------------------------------- ### Update iNatClient Settings After Initialization Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Demonstrates how to modify client settings such as the session, credentials, default parameters, and dry_run flag after the client has been created. ```python client.session = ClientSession() client.creds['username'] = 'my_inaturalist_username' client.default_params['locale'] = 'es' client.dry_run = True ``` -------------------------------- ### GET /observations Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/general.md Retrieves observations from iNaturalist based on specified filters, such as user IDs. ```APIDOC ## GET /observations ### Description Fetches a list of observations from iNaturalist. The library handles conversion of Python lists into the comma-separated strings required by the underlying API. ### Method GET ### Endpoint /observations ### Parameters #### Query Parameters - **user_id** (list/string) - Optional - A list of usernames or IDs to filter observations by. ### Request Example ```python from pyinaturalist import get_observations get_observations(user_id=['tiwane', 'jdmore']) ``` ### Response #### Success Response (200) - **results** (list) - A list of observation objects containing details like taxon, location, and date. #### Response Example { "total_results": 2, "results": [ { "id": 12345, "user": {"login": "tiwane"}, "taxon": {"name": "Species Name"} } ] } ``` -------------------------------- ### Initialize iNatClient with a Custom Session Object Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Illustrates initializing the iNatClient with a pre-configured custom session object. ```python session = MyCustomSession(encabulation_factor=47.2) client = iNatClient(session=session) ``` -------------------------------- ### GET /v1/observations/histogram Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Tutorial_1_Observations.ipynb Retrieves a histogram of observations, allowing filtering by user, time range, and interval. ```APIDOC ## GET /v1/observations/histogram ### Description This endpoint retrieves a histogram of observations. It allows you to view the distribution of observations over a specified period, broken down by a chosen interval (e.g., month, year). ### Method GET ### Endpoint https://api.inaturalist.org/v1/observations/histogram ### Parameters #### Query Parameters - **user_id** (string) - Required - The ID of the user whose observations to include. - **interval** (string) - Required - The interval for the histogram (e.g., 'month', 'year'). - **d1** (string) - Required - The start date for the histogram in ISO 8601 format (e.g., 'YYYY-MM-DD'). - **d2** (string) - Required - The end date for the histogram in ISO 8601 format (e.g., 'YYYY-MM-DD'). ### Request Example ```json { "example": "GET https://api.inaturalist.org/v1/observations/histogram?user_id=jkcook&interval=month&d1=2020-01-01T00:00:00+00:00&d2=2020-12-31T00:00:00+00:00" } ``` ### Response #### Success Response (200) - **results** (array) - An array of objects, where each object represents a time interval and its corresponding observation count. - **date** (object) - The date or time interval. - **year** (integer) - The year. - **month** (integer) - The month (1-12). - **count** (integer) - The number of observations in that interval. #### Response Example ```json { "example": { "results": [ { "date": {"year": 2020, "month": 1}, "count": 5 }, { "date": {"year": 2020, "month": 2}, "count": 1 } // ... more results ] } } ``` ``` -------------------------------- ### GET /taxa/{id} Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Retrieves taxon information with support for localization and preferred place settings. ```APIDOC ## GET /taxa/{id} ### Description Retrieves taxon details. Supports additional parameters for locale and preferred place filtering. ### Method GET ### Endpoint /taxa/{id} ### Parameters #### Query Parameters - **locale** (string) - Optional - Locale preference for taxon names. - **preferred_place_id** (integer) - Optional - Place ID for regional taxon preferences. - **all_names** (boolean) - Optional - Whether to return all known names for the taxon. ### Request Example GET /taxa/123?locale=en&all_names=true ### Response #### Success Response (200) - **id** (integer) - Taxon ID - **name** (string) - Taxon scientific name #### Response Example { "id": 123, "name": "Animalia" } ``` -------------------------------- ### GET /observations Source: https://context7.com/pyinat/pyinaturalist/llms.txt Search for observations with various filters such as taxon, location, date, and quality grade. ```APIDOC ## GET /observations ### Description Search for observations using filters like user ID, taxon name, date, and geographic constraints. ### Method GET ### Endpoint /observations ### Parameters #### Query Parameters - **user_id** (string) - Optional - Filter by username or user ID - **taxon_name** (string) - Optional - Filter by scientific or common name - **created_on** (string) - Optional - Filter by date (YYYY-MM-DD) - **photos** (boolean) - Optional - Filter for observations with photos - **geo** (boolean) - Optional - Filter for observations with coordinates - **place_id** (integer) - Optional - Filter by iNaturalist place ID ### Request Example client.observations.search(user_id='my_username', taxon_name='Danaus plexippus') ### Response #### Success Response (200) - **results** (list) - A list of Observation model objects #### Response Example { "results": [ { "id": 57707611, "taxon": {"name": "Danaus plexippus"}, "location": [50.44, -104.61] } ] } ``` -------------------------------- ### Initialize iNatClient with Authorization Code Flow (Python) Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/authentication.md Demonstrates how to initialize the iNatClient using the 'authorization_code' flow. This method is suitable for applications where user interaction is possible to grant access. It requires an app_id and specifies the authentication flow in the credentials dictionary. ```Python from pyinaturalist import iNatClient client = iNatClient(creds={ 'auth_flow': 'authorization_code', 'app_id': '33f27dc63bdf27f4ca6cd95dd', }) ``` -------------------------------- ### Get Life List Metadata Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Endpoint to fetch metadata related to a user's life list. ```APIDOC ## Get Life List Metadata ### Description Fetches metadata associated with a user's life list, which includes all species they have observed. ### Endpoint - `pyinaturalist.get_life_list_metadata()` ### Parameters This endpoint does not require any specific parameters beyond authentication. ``` -------------------------------- ### Initialize Pyinaturalist Client and Configuration Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Data Visualizations - Regional Activity Report.ipynb Sets up the iNatClient for API requests and defines key parameters like PLACE_ID, PLACE_NAME, and YEAR for regional analysis. This is a prerequisite for all subsequent data fetching and visualization tasks. ```python from datetime import datetime import altair as alt import pandas as pd from pyinaturalist import ( get_interval_ranges, iNatClient, ) # Create a client for API requests client = iNatClient() # Adjustable values PLACE_ID = 6 PLACE_NAME = 'Alaska' YEAR = 2020 ``` -------------------------------- ### Get Observations by IDs (V2) Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Enhanced functionality for querying multiple observation IDs in the v2 API. ```APIDOC ## Get Observations by IDs (V2) ### Description Supports querying more than 30 observation IDs at once when using the `get_observations()` function in the v2 API. ### Endpoint - `pyinaturalist.v2.get_observations()` ### Parameters - **observation_ids** (list[int]) - Required - A list of observation IDs to query (can exceed 30). - **order** (str) - Optional - Allows reversing the order of results with 'desc'. ``` -------------------------------- ### Search Species API Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/quickstart_v0.md Example for searching for taxa (species, genera, families, etc.) by name and rank. ```APIDOC ## GET /taxa ### Description Searches for taxa (species, genera, families, etc.) based on various criteria. ### Method GET ### Endpoint /taxa ### Parameters #### Query Parameters - **q** (str) - Required - The search query (e.g., a name). - **rank** (list[str]) - Optional - A list of ranks to filter by (e.g., 'genus', 'family'). ### Request Example ```python from pyinaturalist import get_taxa response = get_taxa(q='vespi', rank=['genus', 'family']) ``` ### Response #### Success Response (200) - **taxa** (list) - A list of taxon objects matching the search criteria. #### Response Example ```json [ { "id": 52747, "rank": "family", "scientific_name": "Vespidae", "common_name": "Hornets, Paper Wasps, Potter Wasps, and Allies" }, { "id": 92786, "rank": "genus", "scientific_name": "Vespicula" } ] ``` ``` -------------------------------- ### Configure Dataset Parameters Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Data Visualizations - Geospatial Mapping with Folium.ipynb Sets up configuration variables for the dataset name, place ID, and taxon ID to be used in subsequent observation fetching and mapping tasks. ```python DATASET_NAME = 'osoyoos_bees' DATASET_FILENAME = f'{DATASET_NAME}.json' DATASET_MAPNAME = f'{DATASET_NAME}.html' PLACE_ID = 121320 TAXON_NAME = 'Epifamily Anthophila' TAXON_ID = 630955 ``` -------------------------------- ### Authenticate via Password Flow Source: https://context7.com/pyinat/pyinaturalist/llms.txt Explains how to obtain an access token using username and password credentials, including support for environment variables and keyring storage. ```python from pyinaturalist import get_access_token, create_observation, set_keyring_credentials # Get access token with explicit credentials access_token = get_access_token( username='my_inaturalist_username', password='my_inaturalist_password', app_id='33f27dc63bdf27f4ca6cd95dd9dcd5df', app_secret='bbce628be722bfe2abd5fc566ba83de4', ) # With keyring credentials stored set_keyring_credentials( username='my_username', password='my_password', app_id='my_app_id', app_secret='my_app_secret', ) access_token = get_access_token() ``` -------------------------------- ### Get Current User Endpoint Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Adds a new endpoint, get_current_user(), to retrieve information about the currently authenticated user. ```python pyinaturalist.get_current_user() ``` -------------------------------- ### Create and Update Observations with Pyinaturalist Source: https://github.com/pyinat/pyinaturalist/blob/main/README.md Demonstrates how to create a new observation with details like taxon ID, date, location, and media, and subsequently update its description and media. It utilizes the `create` and `update` methods from the `ObservationController`. ```python from datetime import datetime new_obs = client.observations.create( taxon_id=54327, # Vespa Crabro observed_on_string=datetime.now(), time_zone='Brussels', description='This is a free text comment for the observation', tag_list='wasp, Belgium', latitude=50.647143, longitude=4.360216, positional_accuracy=50, # GPS accuracy in meters photos=['~/observations/wasp1.jpg', '~/observations/wasp2.jpg'], sounds=['~/observations/recording.wav'], ) client.observations.update( new_obs.id, # Use the observation ID from the result above access_token=token, description='updated description !', photos='~/observations/wasp_nest.jpg', sounds='~/observations/wasp_nest.mp3', ) ``` -------------------------------- ### GET /observations/{id} Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Retrieves detailed information for one or more observations by their unique identifiers. This endpoint replaces the deprecated get_observation method. ```APIDOC ## GET /observations/{id} ### Description Fetches observation details by ID. This method supports multiple IDs and returns full term and value details for annotations. ### Method GET ### Endpoint /observations/{id} ### Parameters #### Path Parameters - **id** (string/list) - Required - The unique identifier or comma-separated list of identifiers for the observations. ### Request Example GET /observations/12345 ### Response #### Success Response (200) - **results** (list) - A list of observation objects containing full annotation details. #### Response Example { "results": [ { "id": 12345, "annotations": [...] } ] } ``` -------------------------------- ### Configure Session Rate Limiting Source: https://context7.com/pyinat/pyinaturalist/llms.txt Demonstrates how to control request frequency using ClientSession or iNatClient. Includes settings for per-minute/per-second limits, custom storage paths, and distributed file locking. ```python from pyinaturalist import ClientSession, iNatClient, get_taxa # Create session with custom rate limits session = ClientSession(per_minute=50) # 50 requests per minute get_taxa(q='warbler', session=session) # Sub-second rate limiting session = ClientSession(per_second=0.5) # 1 request every 2 seconds # Use with iNatClient client = iNatClient(per_minute=50, per_second=1) # Custom rate limit storage path session = ClientSession(ratelimit_path='/tmp/ratelimit.db') # Enable file locking for distributed applications session = ClientSession(use_file_lock=True) # Requires: pip install filelock ``` -------------------------------- ### Get Life List Metadata Endpoint Source: https://github.com/pyinat/pyinaturalist/blob/main/HISTORY.md Introduces a new Taxon endpoint, get_life_list_metadata(), for fetching metadata related to life lists. ```python pyinaturalist.get_life_list_metadata() ``` -------------------------------- ### Fetch All Paginated Observation Results Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/client.md Demonstrates fetching all results from a paginated observation search at once using the `.all()` method. ```python query = client.observations.search(user_id='my_username', taxon_name='Danaus plexippus') observations = query.all() ``` -------------------------------- ### Authenticate with iNaturalist Source: https://github.com/pyinat/pyinaturalist/blob/main/docs/user_guide/quickstart_v0.md Shows how to obtain an access token using user credentials and an application ID/secret for authorized API requests. ```python token = get_access_token( username='my_username', password='my_password', app_id='my_app_id', app_secret='my_app_secret', ) ``` -------------------------------- ### GET Observations by User ID Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Tutorial_1_Observations.ipynb This snippet demonstrates how to fetch observations for a specific user, with options to filter by ID, set pagination, and order the results. ```APIDOC ## GET /v1/observations ### Description Fetches observations associated with a given user ID. Supports filtering by observation ID, pagination, and ordering. ### Method GET ### Endpoint https://api.inaturalist.org/v1/observations ### Query Parameters - **user_id** (integer) - Required - The ID of the user whose observations to retrieve. - **id_above** (integer) - Optional - Filter observations with an ID greater than this value. - **per_page** (integer) - Optional - The number of results to return per page. Defaults to 20. - **order_by** (string) - Optional - Field to order the results by. Common values include 'id', 'observed_on', 'created_at'. - **order** (string) - Optional - The order of the results. 'asc' for ascending, 'desc' for descending. ### Request Example ```json { "example": "GET https://api.inaturalist.org/v1/observations?user_id=jkcook&id_above=318247&per_page=200&order_by=id&order=asc" } ``` ### Response #### Success Response (200) - **results** (array) - A list of observation objects. - **total_results** (integer) - The total number of observations matching the query. #### Response Example ```json { "example": "{\"results\": [ { \"id\": 318247, \"observation_uuid\": \"...\" } ], \"total_results\": 100 }" } ``` ``` -------------------------------- ### GET /observations/histogram Source: https://github.com/pyinat/pyinaturalist/blob/main/examples/Tutorial_1_Observations.ipynb Retrieves an observation histogram for a specified user. The default interval is 'month_of_year', aggregating counts across all years. You can also specify an interval and date range for more granular results. ```APIDOC ## Observation Histogram API ### Description This endpoint retrieves a histogram of observations for a given user. It allows for flexible time interval aggregation and date range filtering. ### Method GET ### Endpoint /v1/observations/histogram ### Parameters #### Query Parameters - **user_id** (integer) - Required - The ID of the user whose observations to include. - **interval** (string) - Optional - The time interval for aggregation. Defaults to 'month_of_year'. Other options include 'month', 'week', 'day', 'hour'. - **d1** (string) - Optional - The start date for filtering observations (YYYY-MM-DD). - **d2** (string) - Optional - The end date for filtering observations (YYYY-MM-DD). ### Request Example ```python # Default histogram by month of year histogram = client.observations.histogram(user_id=USERNAME) print(histogram.raw) # Histogram by month for a specific year histogram_monthly = client.observations.histogram( user_id=USERNAME, interval='month', d1='2020-01-01', d2='2020-12-31' ) print(histogram_monthly.raw) ``` ### Response #### Success Response (200) - **raw** (dict) - A dictionary where keys are time units (e.g., month numbers) and values are the corresponding observation counts. #### Response Example ```json { "1": 8, "2": 1, "3": 20, "4": 31, "5": 35, "6": 66, "7": 17, "8": 414, "9": 95, "10": 70, "11": 23, "12": 7 } ``` ```