### Install pygbif Source: https://context7.com/gbif/pygbif/llms.txt Install the stable version from PyPI or the development version from GitHub. ```bash pip install pygbif ``` ```bash pip install git+git://github.com/gbif/pygbif.git#egg=pygbif ``` -------------------------------- ### List Installations Source: https://context7.com/gbif/pygbif/llms.txt Retrieves a list of GBIF installations, with an option to limit the number of results. ```python from pygbif import registry installations = registry.installations(limit=5) ``` -------------------------------- ### Install Release Tools Source: https://github.com/gbif/pygbif/blob/master/RELEASING.md Installs the necessary tools for building and uploading Python packages. Ensure PyPI credentials are configured in ~/.pypirc. ```bash pip3 install --upgrade setuptools build twine ``` -------------------------------- ### Python pygbif Occurrence Module Examples Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Demonstrates various functionalities of the pygbif occurrence module, including searching, getting, counting, and initiating downloads. Ensure GBIF credentials are set if using download endpoints. ```python from pygbif import occurrences as occ occ.search(taxonKey = 3329049) ``` ```python occ.get(key = 1986559641) ``` ```python occ.count(isGeoreferenced = True) ``` ```python occ.download('basisOfRecord = PRESERVED_SPECIMEN') ``` ```python occ.download('taxonKey = 3119195') ``` ```python occ.download('decimalLatitude > 50') ``` ```python occ.download_list(user = "sckott", limit = 5) ``` ```python occ.download_meta(key = "0000099-140929101555934") ``` ```python occ.download_get("0000066-140928181241064") ``` ```python occ.download_sql("SELECT datasetKey, countryCode, COUNT(*) FROM occurrence WHERE continent = 'EUROPE' GROUP BY datasetKey, countryCode") ``` ```python occ.download_describe("simpleCsv") ``` ```python occ.download_citation("0002526-241107131044228") ``` -------------------------------- ### Test Installation from TestPyPI Source: https://github.com/gbif/pygbif/blob/master/RELEASING.md Tests the installation of the package and its dependencies from TestPyPI in an isolated virtual environment. This verifies the release before uploading to the production PyPI. ```bash python3 -m venv test20220623-a ``` ```bash source test20220623-a/bin/activate ``` ```bash pip install --index-url https://test.pypi.org/simple/ --no-deps pygbif==0.6.1.dev1 ``` ```bash pip install pygbif==0.6.1.dev1 ``` -------------------------------- ### Install Development pygbif Source: https://github.com/gbif/pygbif/blob/master/docs/intro/install.md Install the development version of pygbif directly from the GitHub repository using pip. This may require sudo privileges. ```console [sudo] pip install git+git://github.com/gbif/pygbif.git#egg=pygbif ``` -------------------------------- ### Install Stable pygbif Source: https://github.com/gbif/pygbif/blob/master/docs/intro/install.md Install the latest stable version of pygbif using pip. ```console pip install pygbif ``` -------------------------------- ### Install pygbif dependencies and testing tools Source: https://github.com/gbif/pygbif/blob/master/docs/contributing.md Install pygbif in editable mode and add necessary testing packages like nose, vcrpy, and coverage. This is required before running tests for the first time. ```shell pip install -e . pip install nose vcrpy coverage ``` -------------------------------- ### Describe Download Format Source: https://github.com/gbif/pygbif/blob/master/README.rst Get a description of available download formats. ```python occ.download_describe("simpleCsv") ``` -------------------------------- ### Download Describe API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Get available download formats. ```APIDOC ## GET /occurrence/download/describe/{format} ### Description Provides a description of the available download formats. ### Method GET ### Endpoint /occurrence/download/describe/{format} ### Parameters #### Path Parameters - **format** (string) - Required - The format to describe (e.g., 'simpleCsv'). ### Response #### Success Response (200) - **description** (string) - A description of the specified download format. #### Response Example ```json { "description": "A simple CSV format with basic occurrence fields." } ``` ``` -------------------------------- ### Get Species Descriptions Source: https://context7.com/gbif/pygbif/llms.txt Fetches descriptions for a specified species key. ```python from pygbif import species descriptions = species.name_usage(key=5231190, data='descriptions') ``` -------------------------------- ### Describe Download Formats Source: https://context7.com/gbif/pygbif/llms.txt Get information about available download formats and their fields. This helps in choosing the most suitable format for your data needs. ```python # Describe download formats format_info = occ.download_describe("simpleCsv") print(format_info['fields']) ``` -------------------------------- ### Download Get API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Retrieve the content of a completed download. ```APIDOC ## GET /occurrence/download/get/{key} ### Description Retrieves the content of a completed download using its key. Requires GBIF credentials. ### Method GET ### Endpoint /occurrence/download/get/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The unique key of the download. ### Response #### Success Response (200) - **content** (string) - The content of the download file (format depends on download type). #### Response Example ```json "occurrenceID,scientificName,decimalLatitude,decimalLongitude\n123,Homo sapiens,40.7128,-74.0060\n456,Panthera leo, -20.0,30.0" ``` #### NOTE Download endpoints require GBIF credentials. Set them as environment variables (`GBIF_USER`, `GBIF_PWD`) or pass them directly via `user=` and `pwd=` arguments. ``` -------------------------------- ### Get Downloaded File Source: https://github.com/gbif/pygbif/blob/master/README.rst Retrieve the content of a specific download using its key. ```python occ.download_get("0000066-140928181241064") ``` -------------------------------- ### Registry: Organizations, Nodes, Networks, Installations API Source: https://context7.com/gbif/pygbif/llms.txt Access GBIF registry information about organizations, nodes, networks, and installations. ```APIDOC ## Registry: Organizations, Nodes, Networks, Installations ### Description Access GBIF registry information about organizations, nodes, networks, and installations. ### Method GET ### Endpoint /registry/organizations /registry/nodes /registry/networks /registry/installations ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of results to return. - **uuid** (string) - Optional - The unique identifier (UUID) of a specific organization, node, network, or installation. ### Request Example ```python from pygbif import registry # List organizations orgs = registry.organizations(limit=5) for org in orgs['results']: print(f"{org['title']} ({org['country']})") # Get specific organization org = registry.organizations(uuid="07f617d0-c688-11d8-bf62-b8a03c50a862") # List GBIF nodes nodes = registry.nodes(limit=10) # Get node details node = registry.nodes(uuid="4ddd294f-02b7-4359-ac33-0806a9ca2512") # List networks networks = registry.networks(limit=5) # List installations installations = registry.installations(limit=5) ``` ### Response #### Success Response (200) - **results** (array) - A list of organization, node, network, or installation objects. - **count** (integer) - The total number of entries matching the query. #### Response Example ```json { "results": [ { "title": "Example Organization", "country": "US" } ], "count": 50 } ``` ``` -------------------------------- ### Get Download Citation Source: https://github.com/gbif/pygbif/blob/master/README.rst Retrieve the citation for a specific download using its key. ```python occ.download_citation("0002526-241107131044228") ``` -------------------------------- ### Download Meta API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Get metadata for a specific download. ```APIDOC ## GET /occurrence/download/meta/{key} ### Description Retrieves metadata for a specific download using its key. Requires GBIF credentials. ### Method GET ### Endpoint /occurrence/download/meta/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The unique key of the download. ### Response #### Success Response (200) - **downloadKey** (string) - The key of the download. - **status** (string) - The status of the download (e.g., SUCCEEDED, RUNNING, FAILED). #### Response Example ```json { "downloadKey": "0000099-140929101555934", "status": "SUCCEEDED" } ``` #### NOTE Download endpoints require GBIF credentials. Set them as environment variables (`GBIF_USER`, `GBIF_PWD`) or pass them directly via `user=` and `pwd=` arguments. ``` -------------------------------- ### Get Download Metadata Source: https://github.com/gbif/pygbif/blob/master/README.rst Retrieve metadata for a specific download using its key. ```python occ.download_meta(key = "0000099-140929101555934") ``` -------------------------------- ### Download Citation API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Get the citation for a specific download. ```APIDOC ## GET /occurrence/download/citation/{key} ### Description Retrieves the citation for a specific download using its key. ### Method GET ### Endpoint /occurrence/download/citation/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The unique key of the download. ### Response #### Success Response (200) - **citation** (string) - The citation for the download. #### Response Example ```json { "citation": "GBIF.org (2024). Global Biodiversity Information Facility. Occurrence Download {key}. Accessed via pygbif." } ``` ``` -------------------------------- ### Get Species Media Source: https://context7.com/gbif/pygbif/llms.txt Retrieves media assets (images, etc.) associated with a species key. ```python from pygbif import species media = species.name_usage(key=5231190, data='media') ``` -------------------------------- ### Get Species Distribution Data Source: https://context7.com/gbif/pygbif/llms.txt Fetches distribution data for a given species key. ```python from pygbif import species distributions = species.name_usage(key=5231190, data='distributions') ``` -------------------------------- ### Verify Package Functionality Source: https://github.com/gbif/pygbif/blob/master/RELEASING.md After installing from TestPyPI, this Python code snippet demonstrates how to import a module and use a function to verify package functionality. Replace the UUID with a relevant identifier. ```python from pygbif import registry registry.dataset_metrics(uuid='3f8a1297-3259-4700-91fc-acc4170b27ce') ``` -------------------------------- ### Download File and Get Citation Source: https://context7.com/gbif/pygbif/llms.txt Download the actual data file for a completed GBIF download and retrieve its citation. Ensure the download status is 'SUCCEEDED' before attempting to download the file. ```python # Download the file when ready if meta['status'] == 'SUCCEEDED': result = occ.download_get(download_key, path='./downloads') print(f"Downloaded to: {result['path']}") # Get citation for a download citation = occ.download_citation("0235283-220831081235567") print(citation) ``` -------------------------------- ### Get Node Details Source: https://context7.com/gbif/pygbif/llms.txt Fetches details for a specific GBIF node using its UUID. ```python from pygbif import registry node = registry.nodes(uuid="4ddd294f-02b7-4359-ac33-0806a9ca2512") ``` -------------------------------- ### Get Synonyms for a Taxon Source: https://context7.com/gbif/pygbif/llms.txt Retrieve a list of synonyms for a given taxon key. This is important for understanding historical nomenclature and alternative names. ```python # Get synonyms synonyms = species.name_usage(key=5231190, data='synonyms') ``` -------------------------------- ### Registry Module API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/registry.md The pygbif registry module provides access to various GBIF registry endpoints. Below are examples of how to use these endpoints. ```APIDOC ## Registry Module Endpoints ### Description Provides access to various GBIF registry data such as organizations, nodes, networks, installations, and datasets. ### Available Endpoints - organizations - nodes - networks - installations - datasets - dataset_metrics - dataset_suggest - dataset_search ### Example Usage ```python from pygbif import registry # Example: Get dataset metrics for a specific dataset UUID metrics = registry.dataset_metrics(uuid='3f8a1297-3259-4700-91fc-acc4170b27ce') print(metrics) # Example: Search for datasets search_results = registry.dataset_search(q='species') print(search_results) ``` ### Request Body Not applicable for general endpoint listing. Specific endpoints may have request bodies for search or suggestion functionalities. ``` -------------------------------- ### Get Species Vernacular Names Source: https://context7.com/gbif/pygbif/llms.txt Retrieves vernacular names for a given species key. Handles potential missing language information. ```python from pygbif import species vernacular = species.name_usage(key=5231190, data='vernacularNames', limit=20) for v in vernacular.get('results', []): print(f"{v['vernacularName']} ({v.get('language', 'unknown')})") ``` -------------------------------- ### Get Species Usage Details by Key Source: https://context7.com/gbif/pygbif/llms.txt Retrieve detailed information about a specific taxon using its unique key. This includes scientific name, rank, and other taxonomic data. ```python from pygbif import species # Get details for a specific taxon key taxon = species.name_usage(key=5231190) print(f"Name: {taxon['scientificName']}") print(f"Rank: {taxon['rank']}") ``` -------------------------------- ### Get Specific Dataset Details Source: https://context7.com/gbif/pygbif/llms.txt Retrieves detailed information for a single GBIF dataset using its UUID. ```python from pygbif import registry dataset = registry.datasets(uuid="a6998220-7e3a-485d-9cd6-73076bd85657") ``` -------------------------------- ### Get Specific Organization Details Source: https://context7.com/gbif/pygbif/llms.txt Fetches details for a specific GBIF organization using its UUID. ```python from pygbif import registry org = registry.organizations(uuid="07f617d0-c688-11d8-bf62-b8a03c50a862") ``` -------------------------------- ### Get Dataset Contacts Source: https://context7.com/gbif/pygbif/llms.txt Fetches the contact information for a specific GBIF dataset using its UUID. ```python from pygbif import registry contacts = registry.datasets( data='contact', uuid="a6998220-7e3a-485d-9cd6-73076bd85657" ) ``` -------------------------------- ### Get Dataset Metadata Source: https://context7.com/gbif/pygbif/llms.txt Retrieves the metadata for a specific GBIF dataset using its UUID. ```python from pygbif import registry metadata = registry.datasets( data='metadata', uuid="a6998220-7e3a-485d-9cd6-73076bd85657" ) ``` -------------------------------- ### Get Dataset Metrics Source: https://context7.com/gbif/pygbif/llms.txt Fetches metrics, such as occurrence count, for a specific dataset using its UUID. ```python from pygbif import registry metrics = registry.dataset_metrics(uuid='3f8a1297-3259-4700-91fc-acc4170b27ce') print(f"Records: {metrics.get('occurrenceCount')}") ``` -------------------------------- ### Suggest Species Name with pygbif Source: https://github.com/gbif/pygbif/blob/master/docs/modules/species.md Use the name_suggest function to find potential matches for a given species name query. Ensure the pygbif library is installed and the species module is imported. ```python from pygbif import species species.name_suggest(q='Puma concolor') ``` -------------------------------- ### Basic Species Name Suggestion Source: https://context7.com/gbif/pygbif/llms.txt Get a list of taxonomic name suggestions based on a query string. This is useful for autocompleting scientific names in search fields or data entry forms. ```python from pygbif import species # Basic autocomplete suggestions = species.name_suggest(q='Puma concolor') for s in suggestions[:5]: print(f"{s['canonicalName']} ({s['rank']})") ``` -------------------------------- ### Get a map by taxon key Source: https://github.com/gbif/pygbif/blob/master/docs/modules/maps.md Use the maps.map function to retrieve a map associated with a specific taxon key. Ensure the pygbif library is imported. ```python from pygbif import maps maps.map(taxonKey = 2435098) ``` -------------------------------- ### Basic Species Name Backbone Matching Source: https://context7.com/gbif/pygbif/llms.txt Match a scientific name against the GBIF backbone taxonomy to get standardized information like usage name, key, and match type. This is the fundamental step for taxonomic standardization. ```python from pygbif import species # Basic name matching result = species.name_backbone(scientificName="Helianthus annuus") print(f"Matched: {result['usage']['name']}") print(f"Usage key: {result['usage']['key']}") print(f"Match type: {result['diagnostics']['matchType']}") ``` -------------------------------- ### Build and Check Package Source: https://github.com/gbif/pygbif/blob/master/RELEASING.md Removes the old distribution files, builds the new package, and checks its integrity. This is a prerequisite for uploading. ```bash rm -rf dist && python3 -m build ``` ```bash python3 -m twine check dist/* ``` -------------------------------- ### Species Name Lookup with Rank Filter, Habitat, and Facets Source: https://context7.com/gbif/pygbif/llms.txt Refine species name lookups by rank, habitat, and enable faceted search to get counts for different taxonomic attributes. Facets are useful for understanding the distribution of search results. ```python # Search with rank filter results = species.name_lookup(q='Helianthus annuus', rank='SPECIES') # Search by habitat marine = species.name_lookup(habitat='marine', limit=10) terrestrial = species.name_lookup(habitat='terrestrial', limit=10) # Faceted search results = species.name_lookup( facet=['status', 'rank'], limit=0, facetMincount='70000' ) print(results['facets']) ``` -------------------------------- ### Set GBIF Credentials (Environment Variables) Source: https://github.com/gbif/pygbif/blob/master/README.rst Set GBIF username and password as environment variables for download authentication. ```bash export GBIF_USER="your_gbif_username" export GBIF_PWD="your_gbif_password" ``` -------------------------------- ### SQL-Based Download Source: https://context7.com/gbif/pygbif/llms.txt Perform a GBIF download using a custom SQL query. This is an experimental feature and requires specific access permissions. ```python # SQL-based download (experimental, requires access) sql = "SELECT gbifid,countryCode FROM occurrence WHERE genusKey = 2435098" sql_key = occ.download_sql(sql) ``` -------------------------------- ### Upload to PyPI Source: https://github.com/gbif/pygbif/blob/master/RELEASING.md Uploads the already built package to the main PyPI repository. This should only be done after successful testing on TestPyPI. ```bash python3 -m twine upload --repository pypi dist/* ``` -------------------------------- ### Download SQL API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Execute a custom SQL query for download. ```APIDOC ## POST /occurrence/download/sql ### Description Executes a custom SQL query to generate a download. Requires GBIF credentials. ### Method POST ### Endpoint /occurrence/download/sql ### Parameters #### Request Body - **sql** (string) - Required - The SQL query to execute. ### Request Example ```json { "sql": "SELECT datasetKey, countryCode, COUNT(*) FROM occurrence WHERE continent = 'EUROPE' GROUP BY datasetKey, countryCode" } ``` ### Response #### Success Response (200) - **downloadKey** (string) - The key for the initiated download. #### Response Example ```json { "downloadKey": "0000100-140929101555934" } ``` #### NOTE Download endpoints require GBIF credentials. Set them as environment variables (`GBIF_USER`, `GBIF_PWD`) or pass them directly via `user=` and `pwd=` arguments. ``` -------------------------------- ### Configure PyPI Credentials Source: https://github.com/gbif/pygbif/blob/master/RELEASING.md Configuration for accessing PyPI and TestPyPI using an API token. Replace placeholders with your actual tokens. ```ini [pypi] username = __token__ password = [testpypi] username = __token__ password = ``` -------------------------------- ### Occurrences Get API Source: https://github.com/gbif/pygbif/blob/master/demos/pygbif-intro.ipynb Retrieve a specific occurrence record by its key. ```APIDOC ## GET /occurrences/{key} ### Description Retrieves a single occurrence record identified by its unique key. ### Method GET ### Endpoint /occurrences/{key} ### Parameters #### Path Parameters - **key** (integer) - Required - The unique identifier for the occurrence record. ### Request Example ```python from pygbif import occurrences occurrences.get(key = 1258202889) ``` ### Response #### Success Response (200) - **basisOfRecord** (string) - The basis of record for the occurrence. - **bibliographicCitation** (string) - Bibliographic citation for the record. - **catalogNumber** (string) - Catalog number of the specimen. - **class** (string) - The class of the organism. - **classKey** (integer) - The key for the organism's class. - **collectionCode** (string) - Code for the collection. - **collectionID** (string) - ID for the collection. - **continent** (string) - Continent where the occurrence was recorded. - **country** (string) - Country where the occurrence was recorded. - **countryCode** (string) - Code for the country. - **county** (string) - County where the occurrence was recorded. - **crawlId** (integer) - ID of the crawl. - **datasetKey** (string) - The key of the dataset the record belongs to. - **datasetName** (string) - Name of the dataset. - **day** (integer) - Day of the occurrence event. - **decimalLatitude** (float) - Decimal latitude of the occurrence. - **decimalLongitude** (float) - Decimal longitude of the occurrence. - **elevation** (float) - Elevation of the occurrence. - **eventDate** (string) - Date of the occurrence event. - **extensions** (object) - Extended data associated with the occurrence. - **facts** (array) - Factual data points. - **family** (string) - The family of the organism. - **familyKey** (integer) - The key for the organism's family. - **fieldNumber** (string) - Field number associated with the record. - **gbifID** (string) - The GBIF ID of the occurrence. - **genericName** (string) - The generic name. - **genus** (string) - The genus of the organism. - **genusKey** (integer) - The key for the organism's genus. - **geodeticDatum** (string) - Geodetic datum used. - **identifier** (string) - Identifier for the record. - **identifiers** (array) - List of identifiers. - **individualCount** (integer) - Number of individuals. - **institutionCode** (string) - Code for the institution. - **issues** (array) - List of issues associated with the record. - **key** (integer) - The unique key for the occurrence record. - **kingdom** (string) - The kingdom of the organism. - **kingdomKey** (integer) - The key for the organism's kingdom. - **lastCrawled** (string) - Timestamp of the last crawl. - **lastInterpreted** (string) - Timestamp of the last interpretation. - **lastParsed** (string) - Timestamp of the last parse. - **license** (string) - License for the data. - **locality** (string) - Locality description. - **month** (integer) - Month of the occurrence event. - **nomenclaturalCode** (string) - Nomenclatural code used. - **nomenclaturalStatus** (string) - Nomenclatural status. - **occurrenceID** (string) - Occurrence ID. - **order** (string) - The order of the organism. - **orderKey** (integer) - The key for the organism's order. - **ownerInstitutionCode** (string) - Owner institution code. - **phylum** (string) - The phylum of the organism. - **phylumKey** (integer) - The key for the organism's phylum. - **protocol** (string) - Protocol used. - **publishingCountry** (string) - Publishing country. - **publishingOrgKey** (string) - Publishing organization key. - **recordNumber** (string) - Record number. - **recordedBy** (string) - Name of the recorder. - **relations** (array) - Related records. - **rightsHolder** (string) - Rights holder of the data. #### Response Example ```json { "basisOfRecord": "PRESERVED_SPECIMEN", "bibliographicCitation": "http://www.tropicos.org/Specimen/100889255", "catalogNumber": "100889255", "class": "Magnoliopsida", "classKey": 220, "collectionCode": "MO", "collectionID": "http://biocol.org/urn:lsid:biocol.org:col:15859", "continent": "NORTH_AMERICA", "country": "Panama", "countryCode": "PA", "county": "La Pintada", "crawlId": 18, "datasetKey": "7bd65a7a-f762-11e1-a439-00145eb45e9a", "datasetName": "Tropicos", "day": 11, "decimalLatitude": 8.68, "decimalLongitude": -80.60056, "elevation": 753.0, "eventDate": "2016-01-11T00:00:00.000+0000", "extensions": {}, "facts": [], "family": "Juglandaceae", "familyKey": 2499, "fieldNumber": "9", "gbifID": "1258202889", "genericName": "Alfaroa", "genus": "Alfaroa", "genusKey": 7310533, "geodeticDatum": "WGS84", "identifier": "urn:catalog:MO:Tropicos:100889255", "identifiers": [], "individualCount": 3, "institutionCode": "MO", "issues": ["COORDINATE_ROUNDED", "GEODETIC_DATUM_ASSUMED_WGS84"], "key": 1258202889, "kingdom": "Plantae", "kingdomKey": 6, "lastCrawled": "2016-06-06T11:13:54.020+0000", "lastInterpreted": "2016-08-04T03:07:30.466+0000", "lastParsed": "2016-03-21T14:33:34.346+0000", "license": "http://creativecommons.org/licenses/by/4.0/legalcode", "locality": "Corregimiento del Harino. Parque Nacional General de División Omar Torrijos Herrera (PNGDOTH) el Copé, camino hacia La Rica, aproximadamente a 1.5 Km. al NO de la cabaña de visitantes del parque. Parcela Los corazones 1 (PP-Corazones-1).", "month": 1, "nomenclaturalCode": "ICNafp", "nomenclaturalStatus": "No opinion", "occurrenceID": "urn:catalog:MO:Tropicos:100889255", "order": "Fagales", "orderKey": 1354, "ownerInstitutionCode": "MOBOT", "phylum": "Tracheophyta", "phylumKey": 7707728, "protocol": "DWC_ARCHIVE", "publishingCountry": "US", "publishingOrgKey": "90fd6680-349f-11d8-aa2d-b8a03c50a862", "recordNumber": "Flores Jiménez 3724", "recordedBy": "Rodolfo Flores|M. Madrid|Y. Peña|L. De Gracia V.|R. Berenguer|J. Rodríguez|J. Vargas|A. Gonzalez C.|C. López V.|R. Vergara E.|H. Moreno", "relations": [], "rightsHolder": "Missouri Botanical Garden" } ``` ``` -------------------------------- ### Occurrence Get API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Retrieve a specific occurrence record by its key. ```APIDOC ## GET /occurrence/{key} ### Description Retrieves a single occurrence record by its unique key. ### Method GET ### Endpoint /occurrence/{key} ### Parameters #### Path Parameters - **key** (integer) - Required - The unique identifier of the occurrence record. ### Response #### Success Response (200) - **key** (integer) - The unique identifier of the occurrence. - **scientificName** (string) - The scientific name of the species. - **decimalLatitude** (number) - The latitude of the occurrence. - **decimalLongitude** (number) - The longitude of the occurrence. #### Response Example ```json { "key": 1986559641, "scientificName": "Homo sapiens", "decimalLatitude": 40.7128, "decimalLongitude": -74.0060 } ``` ``` -------------------------------- ### Upload to TestPyPI Source: https://github.com/gbif/pygbif/blob/master/RELEASING.md Uploads the built package to the TestPyPI repository for initial verification. This step should be performed before uploading to the main PyPI. ```bash python3 -m twine upload --repository testpypi dist/* ``` -------------------------------- ### Get Specific Occurrence Source: https://github.com/gbif/pygbif/blob/master/README.rst Retrieve a specific occurrence record by its key. ```python occ.get(key = 252408386) ``` -------------------------------- ### Search Institutions with Various Parameters Source: https://github.com/gbif/pygbif/blob/master/docs/modules/institution.md Demonstrates how to search for institutions using different query parameters like keywords, specimen counts, source identifiers, country codes, and type specimen counts. ```python from pygbif import institution as inst inst.search(q="Kansas") ``` ```python inst.search(numberSpecimens = "1000,*") ``` ```python inst.search(source = "IH_IRN") ``` ```python inst.search(country = ["US","GB"]) ``` ```python inst.search(typeSpecimenCount = "10,100") ``` -------------------------------- ### Download Data via SQL Source: https://github.com/gbif/pygbif/blob/master/README.rst Initiate a download of occurrence data using a custom SQL query. ```python occ.download_sql("SELECT gbifid,countryCode FROM occurrence WHERE genusKey = 2435098") ``` -------------------------------- ### Check Download Status and List Downloads Source: https://context7.com/gbif/pygbif/llms.txt Retrieve metadata for a specific download using its key and list recent downloads associated with your account. Useful for monitoring download progress and history. ```python # Check download status meta = occ.download_meta(key=download_key) print(f"Status: {meta['status']}") # List your downloads my_downloads = occ.download_list(limit=5) for dl in my_downloads['results']: print(f"{dl['key']}: {dl['status']}") ``` -------------------------------- ### Request Occurrence Download with Multiple Predicates (AND) Source: https://context7.com/gbif/pygbif/llms.txt Request a bulk download of occurrence data using multiple predicates combined with AND logic. Requires GBIF account credentials. Imports 'occurrences' as 'occ' from pygbif. ```python import os from pygbif import occurrences as occ # Set credentials via environment variables os.environ['GBIF_USER'] = 'your_username' os.environ['GBIF_PWD'] = 'your_password' os.environ['GBIF_EMAIL'] = 'your_email@example.com' # Download with multiple predicates (AND logic) download_key, payload = occ.download([ 'taxonKey = 7264332', 'hasCoordinate = TRUE', 'country = US' ]) ``` -------------------------------- ### Download Occurrences by Taxon Key Source: https://github.com/gbif/pygbif/blob/master/README.rst Initiate a download of occurrences for a specific taxon key. ```python occ.download('taxonKey = 3119195') ``` -------------------------------- ### Generate Basic Taxon Map Source: https://context7.com/gbif/pygbif/llms.txt Creates a basic occurrence density map for a given taxon key. Displays the map using matplotlib. ```python from pygbif import maps out = maps.map(taxonKey=2435098) print(f"Image path: {out.path}") out.plot() # Display with matplotlib ``` -------------------------------- ### Run tests with make test Source: https://github.com/gbif/pygbif/blob/master/docs/contributing.md Execute the test suite for pygbif using the provided Makefile task. This command is used for testing under Python 3. ```shell make test ``` -------------------------------- ### Get Literature Count Only Source: https://context7.com/gbif/pygbif/llms.txt Retrieves only the total count of publications matching the search criteria, without fetching the results themselves. ```python from pygbif import literature count = literature.search(year="2010,2024", limit=0)['count'] print(f"Total publications: {count}") ``` -------------------------------- ### Dataset Suggestions (Autocomplete) Source: https://context7.com/gbif/pygbif/llms.txt Provides dataset suggestions based on a query string and optional type filter, useful for autocomplete features. ```python from pygbif import registry suggestions = registry.dataset_suggest(q="Amazon", type="OCCURRENCE") ``` -------------------------------- ### Count Georeferenced Occurrences Source: https://context7.com/gbif/pygbif/llms.txt Get the count of occurrence records that have been georeferenced. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Count georeferenced records geo_count = occurrences.count(isGeoreferenced=True) ``` -------------------------------- ### List User Downloads Source: https://github.com/gbif/pygbif/blob/master/README.rst List recent downloads initiated by a specific user, with a limit. ```python occ.download_list(user = "sckott", limit = 5) ``` -------------------------------- ### Count Occurrences by Country Source: https://context7.com/gbif/pygbif/llms.txt Get the count of occurrence records for a specific country. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Count by country country_count = occurrences.count(country='CA') ``` -------------------------------- ### Load pygbif Libraries Source: https://github.com/gbif/pygbif/blob/master/docs/docs/usecases.md Import necessary modules from the pygbif library for species and occurrence operations. ```python from pygbif import species as species from pygbif import occurrences as occ ``` -------------------------------- ### Request Occurrence Download with Predicate Source: https://context7.com/gbif/pygbif/llms.txt Request a bulk download of occurrence data using a single predicate. Requires GBIF account credentials to be set via environment variables (GBIF_USER, GBIF_PWD, GBIF_EMAIL). Imports 'occurrences' as 'occ' from pygbif. ```python import os from pygbif import occurrences as occ # Set credentials via environment variables os.environ['GBIF_USER'] = 'your_username' os.environ['GBIF_PWD'] = 'your_password' os.environ['GBIF_EMAIL'] = 'your_email@example.com' # Simple download request with predicate download_key, payload = occ.download('taxonKey = 3119195') print(f"Download key: {download_key}") ``` -------------------------------- ### Species Name Backbone Matching with Hints Source: https://context7.com/gbif/pygbif/llms.txt Improve name matching accuracy by providing hints like kingdom or family. This helps disambiguate names that might otherwise have multiple potential matches. ```python # Match with higher taxonomy hints for disambiguation result = species.name_backbone( scientificName="Helianthus annuus", kingdom="Plantae" ) ``` ```python # Match with rank filter result = species.name_backbone( scientificName="Poa", taxonRank="GENUS", family="Poaceae" ) ``` -------------------------------- ### Count Datasets by Country Source: https://context7.com/gbif/pygbif/llms.txt Get the count of datasets that publish data about a specific country. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Datasets covering a country dataset_counts = occurrences.count_datasets(country='DE') ``` -------------------------------- ### Get Specific Occurrence Record Source: https://github.com/gbif/pygbif/blob/master/demos/pygbif-intro.ipynb Retrieve a detailed record for a specific occurrence using its unique key. Requires the 'occurrences' module. ```python occurrences.get(key = 1258202889) ``` -------------------------------- ### Get Parent or Children Taxa Source: https://context7.com/gbif/pygbif/llms.txt Retrieve the direct parent or children taxa for a given taxon key. This helps in navigating the taxonomic hierarchy. ```python # Get parent taxa parents = species.name_usage(key=5231190, data='parents') # Get children taxa children = species.name_usage(key=2435099, data='children') ``` -------------------------------- ### Request Occurrence Download with OR Logic Source: https://context7.com/gbif/pygbif/llms.txt Request a bulk download of occurrence data using multiple predicates combined with OR logic. Requires GBIF account credentials. Imports 'occurrences' as 'occ' from pygbif. ```python import os from pygbif import occurrences as occ # Set credentials via environment variables os.environ['GBIF_USER'] = 'your_username' os.environ['GBIF_PWD'] = 'your_password' os.environ['GBIF_EMAIL'] = 'your_email@example.com' # Download with OR logic download_key, payload = occ.download( ['decimalLatitude >= 65', 'decimalLatitude <= -65'], pred_type='or' ) ``` -------------------------------- ### Get Taxonomic Keys from Names Source: https://github.com/gbif/pygbif/blob/master/docs/docs/usecases.md Retrieve GBIF backbone taxonomic keys for a list of scientific names. This is a prerequisite for fetching occurrence data. ```python splist = ['Cyanocitta stelleri', 'Junco hyemalis', 'Aix sponsa', 'Ursus americanus', 'Pinus conorta', 'Poa annuus'] keys = [ species.name_backbone(x)['usageKey'] for x in splist ] ``` -------------------------------- ### Count Publishing Countries for Data About a Country Source: https://context7.com/gbif/pygbif/llms.txt Get the count of countries that are publishing data about a specified country. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Publishing countries for data about a country pub_counts = occurrences.count_publishingcountries(country='DE') ``` -------------------------------- ### Search Datasets by Keyword Source: https://context7.com/gbif/pygbif/llms.txt Searches for GBIF datasets using a keyword query. ```python from pygbif import registry results = registry.dataset_search(q="amazon", limit=10) ``` -------------------------------- ### Count Occurrences by Year Range Source: https://context7.com/gbif/pygbif/llms.txt Get occurrence counts aggregated by year within a specified range. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Count by year range year_counts = occurrences.count_year(year='1990,2000') for year, count in year_counts.items(): print(f"{year}: {count}") ``` -------------------------------- ### Complex Nested Query for Downloads Source: https://context7.com/gbif/pygbif/llms.txt Construct a complex, nested query using a dictionary format for GBIF downloads. This is useful for specifying multiple criteria and logical operators. ```python query = { "type": "and", "predicates": [ {"type": "in", "key": "TAXON_KEY", "values": ["2387246", "2399391"]}, {"type": "isNotNull", "parameter": "YEAR"}, {"type": "greaterThanOrEquals", "key": "YEAR", "value": "2000"} ] } download_key, payload = occ.download(query) ``` -------------------------------- ### Count Occurrences by Basis of Record Category Source: https://context7.com/gbif/pygbif/llms.txt Get counts of occurrences aggregated by their basis of record category. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Get counts by basis of record category bor_counts = occurrences.count_basisofrecord() for item in bor_counts: print(f"{item['basisOfRecord']}: {item['count']}") ``` -------------------------------- ### Count Occurrences by Basis of Record Source: https://context7.com/gbif/pygbif/llms.txt Get the count of occurrence records for a specific basis of record type. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Count by basis of record obs_count = occurrences.count(basisOfRecord='OBSERVATION') ``` -------------------------------- ### Paging Through Species Name Lookup Results Source: https://context7.com/gbif/pygbif/llms.txt Retrieve results in pages by using the 'limit' and 'offset' parameters. This is essential for handling large result sets efficiently. ```python # Paging through results first_page = species.name_lookup(q='mammalia', limit=100, offset=0) second_page = species.name_lookup(q='mammalia', limit=100, offset=100) ``` -------------------------------- ### Count Georeferenced Occurrences with pygbif Source: https://github.com/gbif/pygbif/blob/master/demos/pygbif-intro.ipynb Use the occurrences.count() method to get the total number of georeferenced occurrences. This is useful for quickly assessing the dataset size. ```python occurrences.count(isGeoreferenced = True) ``` -------------------------------- ### Create and Sort Species Occurrence Data Source: https://github.com/gbif/pygbif/blob/master/docs/docs/usecases.md Combine species names with their corresponding occurrence counts into a dictionary, then sort the items in descending order based on the count. ```python x = dict(zip(splist, out)) sorted(x.items(), key=lambda z:z[1], reverse=True) ``` -------------------------------- ### List GBIF Datasets Source: https://context7.com/gbif/pygbif/llms.txt Retrieves a list of GBIF datasets, with an option to limit the number of results. ```python from pygbif import registry datasets = registry.datasets(limit=5) for ds in datasets['results']: print(f"{ds['title']} ({ds['key']})") ``` -------------------------------- ### Count Total Occurrences Source: https://context7.com/gbif/pygbif/llms.txt Get the total count of occurrence records matching specific filters, such as by taxon key. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Total count with filters total = occurrences.count(taxonKey=3329049) print(f"Total occurrences: {total}") ``` -------------------------------- ### Generate Map Tile Source: https://github.com/gbif/pygbif/blob/master/README.rst Generate a map tile for a given taxon key and year, with specified binning and style. ```python from pygbif import maps out = maps.map(taxonKey = 212, year = 1998, bin = "hex", hexPerTile = 30, style = "classic-noborder.poly") out.response out.path out.img out.plot() ``` -------------------------------- ### Get Single Occurrence Record Source: https://context7.com/gbif/pygbif/llms.txt Retrieve detailed interpreted information for a specific occurrence record using its GBIF key. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Get interpreted occurrence record record = occurrences.get(key=1258202889) print(f"Species: {record['species']}") print(f"Location: {record['decimalLatitude']}, {record['decimalLongitude']}") print(f"Recorded: {record.get('eventDate')}") ``` -------------------------------- ### Search literature using pygbif Source: https://github.com/gbif/pygbif/blob/master/docs/modules/literature.md Use the `lit.search` function to find literature references. Specify your query with `q` and control the number of results with `limit`. ```python from pygbif import literature as lit lit.search(q='climate change', limit=5) ``` -------------------------------- ### Generate Taxon Map with Different Style Source: https://context7.com/gbif/pygbif/llms.txt Generates an occurrence density map for a taxon using a different visual style. ```python from pygbif import maps out = maps.map(taxonKey=2480498, style='purpleYellow.point') out.plot() ``` -------------------------------- ### Get Verbatim Occurrence Data Source: https://context7.com/gbif/pygbif/llms.txt Retrieve the original, uninterpreted verbatim data for a specific occurrence record using its GBIF key. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Get verbatim (original) data without interpretation verbatim = occurrences.get_verbatim(key=1258202889) ``` -------------------------------- ### Download Occurrences by Latitude Source: https://github.com/gbif/pygbif/blob/master/README.rst Initiate a download of occurrences within a specified latitude range. ```python occ.download('decimalLatitude > 50') ``` -------------------------------- ### Basic Species Name Lookup Source: https://context7.com/gbif/pygbif/llms.txt Perform a full-text search across all GBIF taxonomies. Returns a count of matches and basic information for the first few results. ```python from pygbif import species # Basic lookup results = species.name_lookup(q='mammalia') print(f"Found {results['count']} matches") ``` -------------------------------- ### Get Raw Occurrence Fragment Source: https://context7.com/gbif/pygbif/llms.txt Retrieve the raw fragment data (original XML or JSON) for a specific occurrence record using its GBIF key. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Get raw fragment data (original XML or JSON) fragment = occurrences.get_fragment(key=1052909293) ``` -------------------------------- ### Download List API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md List recent downloads for a user. ```APIDOC ## GET /occurrence/download/list ### Description Retrieves a list of recent downloads initiated by a user. Requires GBIF credentials. ### Method GET ### Endpoint /occurrence/download/list ### Parameters #### Query Parameters - **user** (string) - Optional - The username to list downloads for. Defaults to the authenticated user. - **limit** (integer) - Optional - The maximum number of downloads to return. ### Response #### Success Response (200) - **downloads** (array) - A list of download objects. #### Response Example ```json { "downloads": [ { "downloadKey": "0000066-140928181241064", "created": "2024-01-01T10:00:00Z" } ] } ``` #### NOTE Download endpoints require GBIF credentials. Set them as environment variables (`GBIF_USER`, `GBIF_PWD`) or pass them directly via `user=` and `pwd=` arguments. ``` -------------------------------- ### Faceted Occurrence Search Source: https://context7.com/gbif/pygbif/llms.txt Perform a faceted search to get value distributions for specified facets like country and basisOfRecord. Set limit to 0 to only retrieve facets. Requires importing the 'occurrences' module from pygbif. ```python from pygbif import occurrences # Faceted search to get value distributions results = occurrences.search( facet=['country', 'basisOfRecord'], limit=0 ) print(results['facets']['country']) ``` -------------------------------- ### Species Usage Lookup by Name and Rank Source: https://context7.com/gbif/pygbif/llms.txt Find taxon usage information by providing a scientific name and optionally filtering by rank. Useful for confirming taxonomic details when the key is unknown. ```python # Search by name results = species.name_usage(name='Puma', rank='GENUS') ``` -------------------------------- ### Download Occurrences by Basis of Record Source: https://github.com/gbif/pygbif/blob/master/README.rst Initiate a download of occurrences filtered by basis of record. ```python occ.download('basisOfRecord = PRESERVED_SPECIMEN') ``` -------------------------------- ### Generate Taxon Map with Year Filter Source: https://context7.com/gbif/pygbif/llms.txt Generates an occurrence density map for a taxon, filtered by a specific range of years. ```python from pygbif import maps out = maps.map(taxonKey=2480498, year=range(2008, 2012)) out.plot() ``` -------------------------------- ### Occurrence Download API Source: https://github.com/gbif/pygbif/blob/master/docs/modules/occurrence.md Initiate a download of occurrence data based on a query. ```APIDOC ## POST /occurrence/download ### Description Initiates a download of occurrence data based on a query string. Requires GBIF credentials. ### Method POST ### Endpoint /occurrence/download ### Parameters #### Request Body - **query** (string) - Required - The query string to filter occurrences for download (e.g., 'basisOfRecord = PRESERVED_SPECIMEN', 'taxonKey = 3119195', 'decimalLatitude > 50'). ### Request Example ```json { "query": "basisOfRecord = PRESERVED_SPECIMEN" } ``` ### Response #### Success Response (200) - **downloadKey** (string) - The key for the initiated download. #### Response Example ```json { "downloadKey": "0000099-140929101555934" } ``` #### NOTE Download endpoints require GBIF credentials. Set them as environment variables (`GBIF_USER`, `GBIF_PWD`) or pass them directly via `user=` and `pwd=` arguments. ```