Skip to content

Species API

The Species API provides comprehensive endpoints for retrieving mosquito species information, including species lists, detailed species data, and disease vector information.

Endpoints Overview

Method Endpoint Description
GET /species Retrieve paginated list of species with optional search
GET /species/{species_id} Get detailed information for a specific species
GET /vector-species Retrieve species that are disease vectors

Router Implementation

Species router module for the Culicidae Lab Server.

This module provides FastAPI route handlers for mosquito species-related operations in the Culicidae Lab application. It handles retrieval of species information, including species lists, detailed species information, and disease vector species.

The router integrates with the species service layer to perform database queries and return properly formatted responses according to the defined Pydantic schemas.

Routes
  • GET /species: Retrieve a paginated list of mosquito species with optional search
  • GET /species/{species_id}: Retrieve detailed information for a specific species
  • GET /vector-species: Retrieve species that are known disease vectors
Example

The router is typically mounted in the main FastAPI application:

from fastapi import FastAPI
from backend.routers.species import router as species_router

app = FastAPI()
app.include_router(species_router, prefix="/api/v1")

SpeciesBase

Base model for species information.

Contains core species identification fields used across different species-related models.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

SpeciesDetail

Detailed species model with extended information.

Extends the base species model with additional descriptive fields for comprehensive species information.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

SpeciesListResponse

Response model for paginated species lists.

Contains the total count and list of species for API responses.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

get_species_list_endpoint(request: Request, db: DBConnection = Depends(get_db), search: str | None = Query(None), limit: int = Query(50), lang: str = Query(en)) async

Retrieve a list of mosquito species, optionally filtered by a search term.

This endpoint allows clients to fetch a paginated list of mosquito species from the database. The search functionality supports partial matching against scientific names and common names in English and Russian.

Parameters:

Name Type Description Default
request Request

The FastAPI request object used for URL construction.

required
db DBConnection

LanceDB database connection for querying species data.

Depends(get_db)
search str | None

Optional search term to filter species by name. Supports partial matching against scientific names and common names in multiple languages.

Query(None)
limit int

Maximum number of species to return (1-200). Defaults to 50.

Query(50)
lang str

Language code for response localization (e.g., 'en', 'es', 'ru').

Query(en)

Returns:

Name Type Description
SpeciesListResponse

A response containing the count of species and the list of species matching the criteria.

Example

Get the first 25 mosquito species in English:

import httpx

async with httpx.AsyncClient() as client:
    response = await client.get(
        "http://localhost:8000/api/v1/species",
        params={"limit": 25, "lang": "en"}
    )
    species_data = response.json()
    print(f"Found {species_data['count']} species")

Search for species containing "aedes":

response = await client.get(
    "http://localhost:8000/api/v1/species",
    params={"search": "aedes", "limit": 10, "lang": "en"}
)
Source code in backend\routers\species.py
@router.get("/species", response_model=SpeciesListResponse)
async def get_species_list_endpoint(
    request: Request,
    db: lancedb.DBConnection = Depends(database.get_db),
    search: str | None = Query(None, description="Search term for species name"),
    limit: int = Query(50, ge=1, le=200, description="Number of results to return"),
    lang: str = Query("en", description="Language code for response (e.g., 'en', 'es')"),
):
    """
    Retrieve a list of mosquito species, optionally filtered by a search term.

    This endpoint allows clients to fetch a paginated list of mosquito species
    from the database. The search functionality supports partial matching against
    scientific names and common names in English and Russian.

    Args:
        request: The FastAPI request object used for URL construction.
        db: LanceDB database connection for querying species data.
        search: Optional search term to filter species by name. Supports partial
            matching against scientific names and common names in multiple languages.
        limit: Maximum number of species to return (1-200). Defaults to 50.
        lang: Language code for response localization (e.g., 'en', 'es', 'ru').

    Returns:
        SpeciesListResponse: A response containing the count of species and the
            list of species matching the criteria.

    Raises:
        No exceptions are raised directly by this endpoint, but database errors
        may be logged and an empty result returned.

    Example:
        Get the first 25 mosquito species in English:

        ```python
        import httpx

        async with httpx.AsyncClient() as client:
            response = await client.get(
                "http://localhost:8000/api/v1/species",
                params={"limit": 25, "lang": "en"}
            )
            species_data = response.json()
            print(f"Found {species_data['count']} species")
        ```

        Search for species containing "aedes":

        ```python
        response = await client.get(
            "http://localhost:8000/api/v1/species",
            params={"search": "aedes", "limit": 10, "lang": "en"}
        )
        ```
    """
    species_list = species_service.get_all_species(db, request, lang=lang, search=search, limit=limit)
    return SpeciesListResponse(count=len(species_list), species=species_list)

get_species_detail_endpoint(species_id: str, request: Request, region_cache: dict[str, dict[str, str]] = Depends(get_region_cache), db: DBConnection = Depends(get_db), lang: str = Query(en)) async

Retrieve detailed information for a specific mosquito species by ID.

This endpoint fetches comprehensive information about a single mosquito species including its scientific name, common names in multiple languages, vector status, habitat preferences, geographic regions, and associated diseases. The response includes translated content based on the requested language.

Parameters:

Name Type Description Default
species_id str

The unique identifier for the species (e.g., 'aedes-aegypti').

required
request Request

The FastAPI request object used for URL construction.

required
region_cache dict[str, dict[str, str]]

Pre-loaded cache of region translations for localization.

Depends(get_region_cache)
db DBConnection

LanceDB database connection for querying species data.

Depends(get_db)
lang str

Language code for response localization (e.g., 'en', 'es', 'ru').

Query(en)

Returns:

Name Type Description
SpeciesDetail

Detailed information about the requested species including scientific name, common names, descriptions, characteristics, habitat preferences, geographic regions, and related diseases.

Raises:

Type Description
HTTPException

If the species with the given ID is not found, returns a 404 status code with detail message "Species not found".

Example

Get detailed information for Aedes aegypti in English:

import httpx

async with httpx.AsyncClient() as client:
    response = await client.get(
        "http://localhost:8000/api/v1/species/aedes-aegypti",
        params={"lang": "en"}
    )
    if response.status_code == 200:
        species = response.json()
        print(f"Species: {species['scientific_name']}")
        print(f"Common name: {species['common_name']}")
        print(f"Vector status: {species['vector_status']}")
    else:
        print("Species not found")

Get species information in Spanish:

response = await client.get(
    "http://localhost:8000/api/v1/species/anopheles-gambiae",
    params={"lang": "es"}
)
Source code in backend\routers\species.py
@router.get("/species/{species_id}", response_model=SpeciesDetail)
async def get_species_detail_endpoint(
    species_id: str,
    request: Request,
    region_cache: dict[str, dict[str, str]] = Depends(get_region_cache),
    db: lancedb.DBConnection = Depends(database.get_db),
    lang: str = Query("en", description="Language code for response (e.g., 'en', 'es')"),
):
    """
    Retrieve detailed information for a specific mosquito species by ID.

    This endpoint fetches comprehensive information about a single mosquito species
    including its scientific name, common names in multiple languages, vector status,
    habitat preferences, geographic regions, and associated diseases. The response
    includes translated content based on the requested language.

    Args:
        species_id: The unique identifier for the species (e.g., 'aedes-aegypti').
        request: The FastAPI request object used for URL construction.
        region_cache: Pre-loaded cache of region translations for localization.
        db: LanceDB database connection for querying species data.
        lang: Language code for response localization (e.g., 'en', 'es', 'ru').

    Returns:
        SpeciesDetail: Detailed information about the requested species including
            scientific name, common names, descriptions, characteristics, habitat
            preferences, geographic regions, and related diseases.

    Raises:
        HTTPException: If the species with the given ID is not found, returns a
            404 status code with detail message "Species not found".

    Example:
        Get detailed information for Aedes aegypti in English:

        ```python
        import httpx

        async with httpx.AsyncClient() as client:
            response = await client.get(
                "http://localhost:8000/api/v1/species/aedes-aegypti",
                params={"lang": "en"}
            )
            if response.status_code == 200:
                species = response.json()
                print(f"Species: {species['scientific_name']}")
                print(f"Common name: {species['common_name']}")
                print(f"Vector status: {species['vector_status']}")
            else:
                print("Species not found")
        ```

        Get species information in Spanish:

        ```python
        response = await client.get(
            "http://localhost:8000/api/v1/species/anopheles-gambiae",
            params={"lang": "es"}
        )
        ```
    """
    species_detail = species_service.get_species_by_id(db, species_id, lang, region_cache, request)
    if not species_detail:
        raise HTTPException(status_code=404, detail="Species not found")
    return species_detail

get_vector_species_endpoint(request: Request, db: DBConnection = Depends(get_db), disease_id: str | None = Query(None), lang: str = Query(en)) async

Retrieve mosquito species that are disease vectors, optionally filtered by disease.

This endpoint returns a list of mosquito species known to be vectors for various diseases. When a specific disease ID is provided, only species that are vectors for that particular disease are returned. Without a disease filter, all species marked as vectors (excluding 'None' and 'Unknown' status) are returned.

Parameters:

Name Type Description Default
request Request

The FastAPI request object used for URL construction.

required
db DBConnection

LanceDB database connection for querying species data.

Depends(get_db)
disease_id str | None

Optional specific disease ID to filter vectors. If provided, only species that are vectors for this disease will be returned.

Query(None)
lang str

Language code for response localization (e.g., 'en', 'es', 'ru').

Query(en)

Returns:

Type Description

list[SpeciesBase]: A list of mosquito species that are disease vectors, filtered by the specified criteria.

Example

Get all mosquito species that are disease vectors in English:

import httpx

async with httpx.AsyncClient() as client:
    response = await client.get(
        "http://localhost:8000/api/v1/vector-species",
        params={"lang": "en"}
    )
    vector_species = response.json()
    print(f"Found {len(vector_species)} vector species")
    for species in vector_species:
        print(f"- {species['scientific_name']}: {species['vector_status']}")

Get only species that are vectors for malaria:

# First, you'd need to know the disease ID for malaria
response = await client.get(
    "http://localhost:8000/api/v1/vector-species",
    params={"disease_id": "malaria", "lang": "en"}
)
malaria_vectors = response.json()

Get vector species in Russian:

response = await client.get(
    "http://localhost:8000/api/v1/vector-species",
    params={"lang": "ru"}
)
Source code in backend\routers\species.py
@router.get("/vector-species", response_model=list[SpeciesBase])
async def get_vector_species_endpoint(
    request: Request,
    db: lancedb.DBConnection = Depends(database.get_db),
    disease_id: str | None = Query(None, description="Filter vectors by disease ID"),
    lang: str = Query("en", description="Language code for response (e.g., 'en', 'es')"),
):
    """
    Retrieve mosquito species that are disease vectors, optionally filtered by disease.

    This endpoint returns a list of mosquito species known to be vectors for various
    diseases. When a specific disease ID is provided, only species that are vectors
    for that particular disease are returned. Without a disease filter, all species
    marked as vectors (excluding 'None' and 'Unknown' status) are returned.

    Args:
        request: The FastAPI request object used for URL construction.
        db: LanceDB database connection for querying species data.
        disease_id: Optional specific disease ID to filter vectors. If provided,
            only species that are vectors for this disease will be returned.
        lang: Language code for response localization (e.g., 'en', 'es', 'ru').

    Returns:
        list[SpeciesBase]: A list of mosquito species that are disease vectors,
            filtered by the specified criteria.

    Raises:
        No exceptions are raised directly by this endpoint, but database errors
        may be logged and an empty result returned.

    Example:
        Get all mosquito species that are disease vectors in English:

        ```python
        import httpx

        async with httpx.AsyncClient() as client:
            response = await client.get(
                "http://localhost:8000/api/v1/vector-species",
                params={"lang": "en"}
            )
            vector_species = response.json()
            print(f"Found {len(vector_species)} vector species")
            for species in vector_species:
                print(f"- {species['scientific_name']}: {species['vector_status']}")
        ```

        Get only species that are vectors for malaria:

        ```python
        # First, you'd need to know the disease ID for malaria
        response = await client.get(
            "http://localhost:8000/api/v1/vector-species",
            params={"disease_id": "malaria", "lang": "en"}
        )
        malaria_vectors = response.json()
        ```

        Get vector species in Russian:

        ```python
        response = await client.get(
            "http://localhost:8000/api/v1/vector-species",
            params={"lang": "ru"}
        )
        ```
    """
    vector_species = species_service.get_vector_species(db, request, lang=lang, disease_id=disease_id)
    return vector_species

get_region_cache(request: Request) -> dict[str, dict[str, str]]

Dependency for the regions translation cache.

Provides access to the cached region translations data, which maps region codes to translated names in multiple languages.

Parameters:

Name Type Description Default
request Request

The FastAPI request object containing app state.

required

Returns:

Type Description
dict[str, dict[str, str]]

dict[str, dict[str, str]]: Dictionary mapping language codes to region translation dictionaries.

Example

@app.get("/regions/{language}") async def get_regions_by_language( regions: dict = Depends(get_region_cache), language: str = "en" ): return regions.get(language, {})

Source code in backend\dependencies.py
def get_region_cache(request: Request) -> dict[str, dict[str, str]]:
    """Dependency for the regions translation cache.

    Provides access to the cached region translations data, which maps
    region codes to translated names in multiple languages.

    Args:
        request (Request): The FastAPI request object containing app state.

    Returns:
        dict[str, dict[str, str]]: Dictionary mapping language codes to region
            translation dictionaries.

    Example:
        >>> @app.get("/regions/{language}")
        >>> async def get_regions_by_language(
        >>>     regions: dict = Depends(get_region_cache),
        >>>     language: str = "en"
        >>> ):
        >>>     return regions.get(language, {})
    """
    return get_cache(request, "REGION_TRANSLATIONS")

Data Schemas

The Species API uses the following Pydantic schemas for request/response validation:

SpeciesBase Schema

backend.schemas.species_schemas.SpeciesBase

Base model for species information.

Contains core species identification fields used across different species-related models.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

SpeciesDetail Schema

backend.schemas.species_schemas.SpeciesDetail

Detailed species model with extended information.

Extends the base species model with additional descriptive fields for comprehensive species information.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

SpeciesListResponse Schema

backend.schemas.species_schemas.SpeciesListResponse

Response model for paginated species lists.

Contains the total count and list of species for API responses.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Service Layer

The Species API integrates with the species service layer for business logic:

backend.services.species_service

Species data service for managing mosquito species information.

This module provides functionality for retrieving and filtering species data from the database, including support for multiple languages, search functionality, and vector status filtering. It handles the conversion of raw database records to properly formatted species models with localized content.

Example

from backend.services.species_service import get_all_species from backend.services.database import get_db from fastapi import Request db = get_db() species = get_all_species(db, request, "en", search="aedes")

SpeciesBase

Base model for species information.

Contains core species identification fields used across different species-related models.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

SpeciesDetail

Detailed species model with extended information.

Extends the base species model with additional descriptive fields for comprehensive species information.

model_config = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

get_all_species(db: DBConnection, request: Request, lang: str, search: str | None = None, limit: int = 100) -> list[backend.schemas.species_schemas.SpeciesBase]

Retrieve a list of species with optional search filtering.

This function queries the species table and returns species records, optionally filtered by search terms across scientific names and common names in multiple languages. Results are returned as SpeciesBase objects.

Parameters:

Name Type Description Default
db DBConnection

The database connection object.

required
request Request

The FastAPI request object for image URL construction.

required
lang str

The target language code for localized content.

required
search str | None

Search term to filter species by. Searches across scientific names and common names in all languages. If None, returns all species.

None
limit int

Maximum number of species to return. Defaults to 100.

100

Returns:

Type Description
list[SpeciesBase]

list[SpeciesBase]: A list of SpeciesBase objects matching the search criteria, or all species if no search term is provided.

Example

from backend.services.database import get_db db = get_db()

Get all species

all_species = get_all_species(db, request, "en")

Search for Aedes species

aedes_species = get_all_species(db, request, "en", search="aedes")

get_species_by_id(db: DBConnection, species_id: str, lang: str, region_translations: dict[str, dict[str, str]], request: Request) -> backend.schemas.species_schemas.SpeciesDetail | None

Retrieve detailed information for a specific species by its ID.

This function queries the species table for a specific species record and returns it as a detailed SpeciesDetail object with full information including translated region names. Returns None if the species is not found.

Parameters:

Name Type Description Default
db DBConnection

The database connection object.

required
species_id str

The unique identifier for the species to retrieve.

required
lang str

The target language code for localized content.

required
region_translations dict[str, dict[str, str]]

Pre-loaded region translations for localizing geographic region names.

required
request Request

The FastAPI request object for image URL construction.

required

Returns:

Type Description
SpeciesDetail | None

SpeciesDetail | None: A SpeciesDetail object if found, None if the species does not exist in the database.

Example

from backend.services.database import get_db db = get_db() aedes = get_species_by_id(db, "aedes_aegypti", "en", regions, request) if aedes: ... print(f"Species: {aedes.scientific_name}") ... print(f"Regions: {aedes.geographic_regions}")

get_vector_species(db: DBConnection, request: Request, lang: str, disease_id: str | None = None) -> list[backend.schemas.species_schemas.SpeciesBase]

Retrieve species that are disease vectors, optionally filtered by disease.

This function queries the species table for species marked as disease vectors. It can filter by a specific disease to find only species that transmit that disease, or return all vector species if no disease filter is applied.

Parameters:

Name Type Description Default
db DBConnection

The database connection object.

required
request Request

The FastAPI request object for image URL construction.

required
lang str

The target language code for localized content.

required
disease_id str | None

Specific disease ID to filter by. If provided, only species that transmit this disease are returned. If None, all vector species are returned.

None

Returns:

Type Description
list[SpeciesBase]

list[SpeciesBase]: A list of SpeciesBase objects that are disease vectors, optionally filtered by the specified disease.

Example

from backend.services.database import get_db db = get_db()

Get all vector species

all_vectors = get_vector_species(db, request, "en")

Get species that transmit malaria

malaria_vectors = get_vector_species(db, request, "en", "malaria")

get_table(db: DBConnection, table_name: str)

Retrieve a specific table from the LanceDB database.

Opens and returns a reference to the specified table in the database. This function validates that the table exists and is accessible.

Parameters:

Name Type Description Default
db DBConnection

The database connection object.

required
table_name str

The name of the table to retrieve.

required

Returns:

Type Description

lancedb.table.Table: A table object for the specified table name.

Raises:

Type Description
ValueError

If the table is not found or cannot be opened.

Example

db = get_db() observations_table = get_table(db, "observations") results = observations_table.search().limit(10).to_list()

Example Usage

Get Species List

import httpx

async with httpx.AsyncClient() as client:
    response = await client.get(
        "http://localhost:8000/api/v1/species",
        params={"limit": 25, "lang": "en"}
    )
    species_data = response.json()
    print(f"Found {species_data['count']} species")

Search for Species

response = await client.get(
    "http://localhost:8000/api/v1/species",
    params={"search": "aedes", "limit": 10, "lang": "en"}
)

Get Species Details

response = await client.get(
    "http://localhost:8000/api/v1/species/aedes-aegypti",
    params={"lang": "en"}
)
species = response.json()

Get Vector Species

response = await client.get(
    "http://localhost:8000/api/v1/vector-species",
    params={"lang": "en"}
)
vector_species = response.json()