Перейти к содержанию

API фильтров

API фильтров предоставляет endpoints для получения опций фильтров и управления возможностями фильтрации данных на платформе CulicidaeLab.

Реализация роутера

Router module for filter-related API endpoints in CulicidaeLab.

This module provides FastAPI router endpoints for retrieving filter options used throughout the CulicidaeLab application. It handles requests for species, regions, and data source filtering options with multi-language support.

The module includes
  • Filter options endpoint for retrieving available filter criteria
  • Integration with caching dependencies for performance
  • Localization support for multiple languages
Typical usage example

from backend.routers.filters import router app.include_router(router)

Attributes:

Name Type Description
router APIRouter

FastAPI APIRouter instance containing filter-related endpoints.

FilterOptions

Container model for all available filter options.

Provides comprehensive filtering options including species, regions, and data sources for use in API endpoints that support filtering functionality.

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_filter_options_endpoint(lang: str = Query(en), species_names: list[str] = Depends(get_species_cache), region_translations: dict = Depends(get_region_cache), data_source_translations: dict = Depends(get_data_source_cache)) async

Retrieves available filter options for species, regions, and data sources.

This endpoint provides comprehensive filtering options that can be used across the CulicidaeLab application to filter disease data by various criteria.

Parameters:

Name Type Description Default
lang str

Language code for response localization (e.g., 'en' for English, 'es' for Spanish). Defaults to 'en'.

Query(en)
species_names list[str]

List of available mosquito species names for filtering.

Depends(get_species_cache)
region_translations dict

Dictionary mapping region codes to translated names.

Depends(get_region_cache)
data_source_translations dict

Dictionary mapping data source codes to translated names.

Depends(get_data_source_cache)

Returns:

Name Type Description
FilterOptions

A structured response containing: - species: List of available mosquito species with their display names - regions: List of geographical regions with translated names - data_sources: List of data sources with translated names

Example
Get filter options in English

response = await get_filter_options_endpoint("en", [...], {...}, {...}) print(response.species) # List of species options print(response.regions) # List of region options

Get filter options in Spanish

response = await get_filter_options_endpoint("es", [...], {...}, {...}) print(response.species) # Lista de opciones de especies

Source code in backend\routers\filters.py
@router.get("/filter_options", response_model=FilterOptions)
async def get_filter_options_endpoint(
    lang: str = Query("en", description="Language code for response (e.g., 'en', 'es')"),
    species_names: list[str] = Depends(get_species_cache),
    region_translations: dict = Depends(get_region_cache),
    data_source_translations: dict = Depends(get_data_source_cache),
):
    """Retrieves available filter options for species, regions, and data sources.

    This endpoint provides comprehensive filtering options that can be used across
    the CulicidaeLab application to filter disease data by various criteria.

    Args:
        lang: Language code for response localization (e.g., 'en' for English,
            'es' for Spanish). Defaults to 'en'.
        species_names: List of available mosquito species names for filtering.
        region_translations: Dictionary mapping region codes to translated names.
        data_source_translations: Dictionary mapping data source codes to translated names.

    Returns:
        FilterOptions: A structured response containing:
            - species: List of available mosquito species with their display names
            - regions: List of geographical regions with translated names
            - data_sources: List of data sources with translated names

    Example:
        >>> # Get filter options in English
        >>> response = await get_filter_options_endpoint("en", [...], {...}, {...})
        >>> print(response.species)  # List of species options
        >>> print(response.regions)  # List of region options

        >>> # Get filter options in Spanish
        >>> response = await get_filter_options_endpoint("es", [...], {...}, {...})
        >>> print(response.species)  # Lista de opciones de especies
    """
    return filter_service.get_filter_options(
        lang=lang,
        species_names=species_names,
        region_translations=region_translations,
        data_source_translations=data_source_translations,
    )

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

Dependency for the data sources translation cache.

Provides access to the cached data source translations, which maps data source 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 data source translation dictionaries.

Example

@app.get("/datasources/{language}") async def get_data_sources_by_language( sources: dict = Depends(get_data_source_cache), language: str = "en" ): return sources.get(language, {})

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

    Provides access to the cached data source translations, which maps
    data source 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 data
            source translation dictionaries.

    Example:
        >>> @app.get("/datasources/{language}")
        >>> async def get_data_sources_by_language(
        >>>     sources: dict = Depends(get_data_source_cache),
        >>>     language: str = "en"
        >>> ):
        >>>     return sources.get(language, {})
    """
    return get_cache(request, "DATASOURCE_TRANSLATIONS")

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")

get_species_cache(request: Request) -> list[str]

Dependency for the species names list cache.

Provides access to the cached list of all available species names for validation and autocomplete functionality.

Parameters:

Name Type Description Default
request Request

The FastAPI request object containing app state.

required

Returns:

Type Description
list[str]

list[str]: List of all available species names in the system.

Example

@app.get("/species") async def get_all_species( species_list: list[str] = Depends(get_species_cache) ): return {"species": species_list}

Source code in backend\dependencies.py
def get_species_cache(request: Request) -> list[str]:
    """Dependency for the species names list cache.

    Provides access to the cached list of all available species names
    for validation and autocomplete functionality.

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

    Returns:
        list[str]: List of all available species names in the system.

    Example:
        >>> @app.get("/species")
        >>> async def get_all_species(
        >>>     species_list: list[str] = Depends(get_species_cache)
        >>> ):
        >>>     return {"species": species_list}
    """
    return get_cache(request, "SPECIES_NAMES")

Схемы данных

API фильтров использует Pydantic схемы для валидации данных фильтров:

backend.schemas.filter_schemas

Pydantic models for filtering functionality.

This module defines the schema models used for filter options in API endpoints across different services.

RegionFilter

Filter model for geographic regions.

Used to represent available regions for filtering observations and species data.

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)

DataSourceFilter

Filter model for data sources.

Used to represent available data sources for filtering observations and species data.

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)

FilterOptions

Container model for all available filter options.

Provides comprehensive filtering options including species, regions, and data sources for use in API endpoints that support filtering functionality.

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)

Слой сервисов

API фильтров интегрируется со слоями сервисов фильтров:

backend.services.filter_service

Filter options service for generating localized filter data.

This module provides functionality for constructing translated filter options from cached data sources, regions, and species information. It supports multiple languages and generates filter objects suitable for frontend consumption.

Example

from backend.services.filter_service import get_filter_options options = get_filter_options( ... lang="en", ... species_names=["Aedes aegypti", "Culex pipiens"], ... region_translations={"en": {"reg1": "Region 1"}}, ... data_source_translations={"en": {"src1": "Source 1"}} ... )

DataSourceFilter

Filter model for data sources.

Used to represent available data sources for filtering observations and species data.

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)

FilterOptions

Container model for all available filter options.

Provides comprehensive filtering options including species, regions, and data sources for use in API endpoints that support filtering functionality.

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)

RegionFilter

Filter model for geographic regions.

Used to represent available regions for filtering observations and species data.

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_filter_options(lang: str, species_names: list[str], region_translations: dict[str, dict[str, str]], data_source_translations: dict[str, dict[str, str]]) -> FilterOptions

Construct translated filter options from pre-loaded, cached data.

This function processes cached translation data to generate filter options for species, regions, and data sources in the specified language. All options are sorted alphabetically for consistent presentation.

Parameters:

Name Type Description Default
lang str

The target language code (e.g., 'en', 'ru') for which to generate translated filter options.

required
species_names list[str]

A list of scientific species names to include in the filter options.

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

A nested dictionary containing region translations structured as {lang: {region_id: name}}.

required
data_source_translations dict[str, dict[str, str]]

A nested dictionary containing data source translations structured as {lang: {source_id: name}}.

required

Returns:

Name Type Description
FilterOptions FilterOptions

A structured object containing sorted filter options for species, regions, and data sources in the specified language.

Example

species = ["Aedes aegypti", "Culex quinquefasciatus"] regions = {"en": {"us": "United States", "br": "Brazil"}} sources = {"en": {"gbif": "GBIF", "citizen": "Citizen Science"}} options = get_filter_options("en", species, regions, sources) print(len(options.regions)) # Number of region options 2

Примеры использования

Получить доступные фильтры

import httpx

async with httpx.AsyncClient() as client:
    # Получить все доступные опции фильтров
    response = await client.get(
        "http://localhost:8000/api/v1/filters",
        params={"lang": "ru"}
    )
    filters = response.json()

    print("Доступные фильтры:")
    for filter_type, options in filters.items():
        print(f"- {filter_type}: {len(options)} опций")

Получить конкретный тип фильтра

# Получить опции фильтра видов
response = await client.get(
    "http://localhost:8000/api/v1/filters/species",
    params={"lang": "ru"}
)
species_filters = response.json()

# Получить опции фильтра регионов
response = await client.get(
    "http://localhost:8000/api/v1/filters/regions",
    params={"lang": "ru"}
)
region_filters = response.json()

# Получить опции фильтра болезней
response = await client.get(
    "http://localhost:8000/api/v1/filters/diseases",
    params={"lang": "ru"}
)
disease_filters = response.json()

Применить фильтры к запросам данных

# Использовать фильтры в запросах видов
response = await client.get(
    "http://localhost:8000/api/v1/species",
    params={
        "region": "north-america",
        "vector_status": "primary",
        "disease": "malaria",
        "lang": "ru"
    }
)
filtered_species = response.json()