API видов¶
API видов предоставляет всеобъемлющие endpoints для получения информации о видах комаров, включая списки видов, детальные данные о видах и информацию о переносчиках болезней.
Обзор endpoints¶
| Метод | Endpoint | Описание |
|---|---|---|
| GET | /species | Получить пагинированный список видов с опциональным поиском |
| GET | /species/{species_id} | Получить детальную информацию для конкретного вида |
| GET | /vector-species | Получить виды, которые являются переносчиками болезней |
Реализация роутера¶
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:
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":
Source code in backend\routers\species.py
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:
Source code in backend\routers\species.py
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:
Source code in backend\routers\species.py
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
Схемы данных¶
API видов использует следующие Pydantic схемы для валидации запросов/ответов:
Схема SpeciesBase¶
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¶
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¶
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)
Слой сервисов¶
API видов интегрируется со слоем сервисов видов для бизнес-логики:
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. |
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. |
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()
Примеры использования¶
Получить список видов¶
import httpx
async with httpx.AsyncClient() as client:
response = await client.get(
"http://localhost:8000/api/v1/species",
params={"limit": 25, "lang": "ru"}
)
species_data = response.json()
print(f"Найдено {species_data['count']} видов")
Поиск видов¶
response = await client.get(
"http://localhost:8000/api/v1/species",
params={"search": "aedes", "limit": 10, "lang": "ru"}
)
Получить детали вида¶
response = await client.get(
"http://localhost:8000/api/v1/species/aedes-aegypti",
params={"lang": "ru"}
)
species = response.json()