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

API болезней

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

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

Disease-related API endpoints for the CulicidaeLab server.

This module provides FastAPI router endpoints for retrieving information about vector-borne diseases and their associated arthropod vectors. The endpoints support multiple languages and provide both list and detail views of diseases.

The module includes the following endpoints: - GET /diseases: Retrieve a paginated list of diseases with optional search filtering - GET /diseases/{disease_id}: Retrieve detailed information for a specific disease - GET /diseases/{disease_id}/vectors: Retrieve vector species associated with a disease

All endpoints support internationalization and return data in the requested language.

Disease

Complete disease model with unique identifier.

Used for responses that include the database ID of the disease.

model_config = {'from_attributes': True} 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)

Config
from_attributes = True class-attribute

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

DiseaseListResponse

Response model for paginated disease lists.

Contains the total count and list of diseases 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)

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)

get_disease_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 vector-borne diseases, optionally filtered by a search term.

This endpoint provides a paginated list of diseases that can be filtered by name or description. Results are localized based on the requested language and support various query parameters for flexible disease discovery and analysis.

Parameters:

Name Type Description Default
request Request

The FastAPI request object containing client information and headers.

required
db DBConnection

Database connection dependency for querying disease data from the LanceDB vector database.

Depends(get_db)
search str | None

Optional search term to filter diseases by name or description. Performs case-insensitive substring matching. If None, returns all diseases. Examples: "malaria", "fever", "mosquito".

Query(None)
limit int

Maximum number of diseases to return per page (1-200). Defaults to 50. Use this parameter for pagination control when dealing with large result sets.

Query(50)
lang str

Language code for response localization and internationalization. Supported languages: 'en' (English), 'es' (Spanish), 'fr' (French), 'pt' (Portuguese). Defaults to 'en' for English responses.

Query(en)

Returns:

Name Type Description
DiseaseListResponse

A structured response containing: - count (int): Total number of diseases matching the search criteria - diseases (list[Disease]): List of disease objects with basic information

Example

Basic disease list retrieval: GET /diseases?limit=10&lang=en

Search for specific diseases: GET /diseases?search=malaria&limit=5&lang=en

Multilingual support: GET /diseases?search=fiebre&lang=en

Response format: { "count": 2, "diseases": [ { "id": "malaria", "name": "Malaria", "description": "A life-threatening disease caused by Plasmodium parasites...", "vectors": ["Anopheles mosquito"] }, { "id": "dengue", "name": "Dengue Fever", "description": "A mosquito-borne viral infection causing flu-like illness...", "vectors": ["Aedes aegypti", "Aedes albopictus"] } ] }

Source code in backend\routers\diseases.py
@router.get("/diseases", response_model=DiseaseListResponse)
async def get_disease_list_endpoint(
    request: Request,
    db: lancedb.DBConnection = Depends(database.get_db),
    search: str | None = Query(None, description="Search term for disease name or description"),
    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 vector-borne diseases, optionally filtered by a search term.

    This endpoint provides a paginated list of diseases that can be filtered by name or description.
    Results are localized based on the requested language and support various query parameters
    for flexible disease discovery and analysis.

    Args:
        request (Request): The FastAPI request object containing client information and headers.
        db (lancedb.DBConnection): Database connection dependency for querying disease data from
            the LanceDB vector database.
        search (str | None): Optional search term to filter diseases by name or description.
            Performs case-insensitive substring matching. If None, returns all diseases.
            Examples: "malaria", "fever", "mosquito".
        limit (int): Maximum number of diseases to return per page (1-200). Defaults to 50.
            Use this parameter for pagination control when dealing with large result sets.
        lang (str): Language code for response localization and internationalization.
            Supported languages: 'en' (English), 'es' (Spanish), 'fr' (French), 'pt' (Portuguese).
            Defaults to 'en' for English responses.

    Returns:
        DiseaseListResponse: A structured response containing:
            - count (int): Total number of diseases matching the search criteria
            - diseases (list[Disease]): List of disease objects with basic information

    Example:
        Basic disease list retrieval:
        GET /diseases?limit=10&lang=en

        Search for specific diseases:
        GET /diseases?search=malaria&limit=5&lang=en

        Multilingual support:
        GET /diseases?search=fiebre&lang=en

        Response format:
        {
            "count": 2,
            "diseases": [
                {
                    "id": "malaria",
                    "name": "Malaria",
                    "description": "A life-threatening disease caused by Plasmodium parasites...",
                    "vectors": ["Anopheles mosquito"]
                },
                {
                    "id": "dengue",
                    "name": "Dengue Fever",
                    "description": "A mosquito-borne viral infection causing flu-like illness...",
                    "vectors": ["Aedes aegypti", "Aedes albopictus"]
                }
            ]
        }
    """
    disease_list = disease_service.get_all_diseases(db, request, lang=lang, search=search, limit=limit)
    return DiseaseListResponse(count=len(disease_list), diseases=disease_list)

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

Retrieve detailed information for a specific disease by ID.

This endpoint provides comprehensive information about a specific vector-borne disease, including its description, associated vectors, symptoms, and other relevant details. Results are localized based on the requested language.

Parameters:

Name Type Description Default
disease_id str

Unique identifier for the disease (e.g., 'malaria', 'dengue'). This is typically the disease name in lowercase with hyphens.

required
request Request

The FastAPI request object containing client information.

required
db DBConnection

Database connection dependency for querying disease data.

Depends(get_db)
lang str

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

Query(en)

Returns:

Name Type Description
Disease

A detailed disease object containing all available information about the specified disease, or None if the disease is not found.

Raises:

Type Description
HTTPException

If the disease with the specified ID is not found (404 status code).

Example

GET /diseases/malaria?lang=en Response: { "id": "malaria", "name": "Malaria", "description": "A life-threatening disease caused by Plasmodium parasites...", "symptoms": ["Fever", "Chills", "Headache"], "vectors": ["Anopheles gambiae", "Anopheles funestus"], "regions": ["Sub-Saharan Africa", "Southeast Asia"], "transmission": "Bite of infected female Anopheles mosquitoes" }

Source code in backend\routers\diseases.py
@router.get("/diseases/{disease_id}", response_model=Disease)
async def get_disease_detail_endpoint(
    disease_id: str,
    request: Request,
    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 disease by ID.

    This endpoint provides comprehensive information about a specific vector-borne disease,
    including its description, associated vectors, symptoms, and other relevant details.
    Results are localized based on the requested language.

    Args:
        disease_id (str): Unique identifier for the disease (e.g., 'malaria', 'dengue').
            This is typically the disease name in lowercase with hyphens.
        request (Request): The FastAPI request object containing client information.
        db (lancedb.DBConnection): Database connection dependency for querying disease data.
        lang (str): Language code for response localization (e.g., 'en', 'es', 'fr').
            Defaults to 'en' for English.

    Returns:
        Disease: A detailed disease object containing all available information about
            the specified disease, or None if the disease is not found.

    Raises:
        HTTPException: If the disease with the specified ID is not found (404 status code).

    Example:
        GET /diseases/malaria?lang=en
        Response:
        {
            "id": "malaria",
            "name": "Malaria",
            "description": "A life-threatening disease caused by Plasmodium parasites...",
            "symptoms": ["Fever", "Chills", "Headache"],
            "vectors": ["Anopheles gambiae", "Anopheles funestus"],
            "regions": ["Sub-Saharan Africa", "Southeast Asia"],
            "transmission": "Bite of infected female Anopheles mosquitoes"
        }
    """
    disease_detail = disease_service.get_disease_by_id(db, disease_id, lang, request)
    if not disease_detail:
        raise HTTPException(status_code=404, detail="Disease not found")
    return disease_detail

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

Retrieve vector species associated with a specific disease.

This endpoint returns a list of arthropod vectors (primarily mosquitoes, ticks, and flies) that are known to transmit the specified disease. This information is crucial for understanding disease transmission patterns and vector control strategies.

Parameters:

Name Type Description Default
disease_id str

Unique identifier for the disease (e.g., 'malaria', 'lyme-disease'). This is typically the disease name in lowercase with hyphens.

required
request Request

The FastAPI request object containing client information.

required
db DBConnection

Database connection dependency for querying species data.

Depends(get_db)
lang str

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

Query(en)

Returns:

Type Description

list[SpeciesBase]: A list of species objects that serve as vectors for the specified disease. Each species includes taxonomic information and habitat details.

Raises:

Type Description
HTTPException

If the disease with the specified ID is not found (404 status code).

Example

GET /diseases/malaria/vectors?lang=en Response: [ { "id": "anopheles-gambiae", "scientific_name": "Anopheles gambiae", "common_name": "African malaria mosquito", "genus": "Anopheles", "family": "Culicidae", "habitat": "Tropical and subtropical regions", "distribution": "Sub-Saharan Africa" }, { "id": "anopheles-funestus", "scientific_name": "Anopheles funestus", "common_name": "Common malaria mosquito", "genus": "Anopheles", "family": "Culicidae", "habitat": "Rural and peri-urban areas", "distribution": "Africa south of the Sahara" } ]

Source code in backend\routers\diseases.py
@router.get("/diseases/{disease_id}/vectors", response_model=list[SpeciesBase])
async def get_disease_vectors_endpoint(
    disease_id: str,
    request: Request,
    db: lancedb.DBConnection = Depends(database.get_db),
    lang: str = Query("en", description="Language code for response (e.g., 'en', 'es')"),
):
    """
    Retrieve vector species associated with a specific disease.

    This endpoint returns a list of arthropod vectors (primarily mosquitoes, ticks, and flies)
    that are known to transmit the specified disease. This information is crucial for
    understanding disease transmission patterns and vector control strategies.

    Args:
        disease_id (str): Unique identifier for the disease (e.g., 'malaria', 'lyme-disease').
            This is typically the disease name in lowercase with hyphens.
        request (Request): The FastAPI request object containing client information.
        db (lancedb.DBConnection): Database connection dependency for querying species data.
        lang (str): Language code for response localization (e.g., 'en', 'es', 'fr').
            Defaults to 'en' for English.

    Returns:
        list[SpeciesBase]: A list of species objects that serve as vectors for the specified
            disease. Each species includes taxonomic information and habitat details.

    Raises:
        HTTPException: If the disease with the specified ID is not found (404 status code).

    Example:
        GET /diseases/malaria/vectors?lang=en
        Response:
        [
            {
                "id": "anopheles-gambiae",
                "scientific_name": "Anopheles gambiae",
                "common_name": "African malaria mosquito",
                "genus": "Anopheles",
                "family": "Culicidae",
                "habitat": "Tropical and subtropical regions",
                "distribution": "Sub-Saharan Africa"
            },
            {
                "id": "anopheles-funestus",
                "scientific_name": "Anopheles funestus",
                "common_name": "Common malaria mosquito",
                "genus": "Anopheles",
                "family": "Culicidae",
                "habitat": "Rural and peri-urban areas",
                "distribution": "Africa south of the Sahara"
            }
        ]
    """
    disease_detail = disease_service.get_disease_by_id(db, disease_id, lang, request)
    if not disease_detail:
        raise HTTPException(status_code=404, detail="Disease not found")

    vector_species = species_service.get_vector_species(db, request, lang=lang, disease_id=disease_id)
    return vector_species

Схемы данных

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

backend.schemas.diseases_schemas

Pydantic models for the Disease service.

This module defines the schema models used for request/response validation in the Disease service endpoints.

DiseaseBase

Base model for disease information.

Contains common fields that can be shared between request and response 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)

Disease

Complete disease model with unique identifier.

Used for responses that include the database ID of the disease.

model_config = {'from_attributes': True} 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)

Config
from_attributes = True class-attribute

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

DiseaseListResponse

Response model for paginated disease lists.

Contains the total count and list of diseases 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.disease_service

Disease data service for managing mosquito-borne disease information.

This module provides functionality for retrieving and filtering disease data from the database, including support for multiple languages, search functionality, and vector-based filtering. It handles the conversion of raw database records to properly formatted disease models.

Example

from backend.services.disease_service import get_all_diseases from backend.services.database import get_db from fastapi import Request db = get_db() diseases = get_all_diseases(db, request, "en", search="malaria")

Disease

Complete disease model with unique identifier.

Used for responses that include the database ID of the disease.

model_config = {'from_attributes': True} 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)

Config
from_attributes = True class-attribute

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

get_all_diseases(db: DBConnection, request: Request, lang: str, search: str | None = None, limit: int = 50) -> list[backend.schemas.diseases_schemas.Disease]

Retrieve a list of diseases with optional search filtering.

This function queries the diseases table and returns disease records, optionally filtered by search terms across multiple language fields. Results are returned as properly formatted Disease 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 diseases by. Searches across name and description fields in all languages. If None, returns all diseases.

None
limit int

Maximum number of diseases to return. Defaults to 50.

50

Returns:

Type Description
list[Disease]

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

Example

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

Get all diseases

all_diseases = get_all_diseases(db, request, "en")

malaria_diseases = get_all_diseases(db, request, "en", search="malaria")

get_disease_by_id(db: DBConnection, disease_id: str, lang: str, request: Request) -> backend.schemas.diseases_schemas.Disease | None

Retrieve detailed information for a specific disease by its ID.

This function queries the diseases table for a specific disease record and returns it as a properly formatted Disease object. Returns None if the disease is not found.

Parameters:

Name Type Description Default
db DBConnection

The database connection object.

required
disease_id str

The unique identifier for the disease to retrieve.

required
lang str

The target language code for localized content.

required
request Request

The FastAPI request object for image URL construction.

required

Returns:

Type Description
Disease | None

Disease | None: A Disease object if found, None if the disease does not exist in the database.

Example

from backend.services.database import get_db db = get_db() malaria = get_disease_by_id(db, "malaria", "en", request) if malaria: ... print(f"Disease: {malaria.name}")

get_diseases_by_vector(db: DBConnection, vector_id: str, lang: str, request: Request) -> list[backend.schemas.diseases_schemas.Disease]

Retrieve diseases associated with a specific mosquito vector species.

This function queries the diseases table for diseases that are transmitted by the specified vector species. The vector relationship is determined by checking if the vector_id exists in the disease's vectors array.

Parameters:

Name Type Description Default
db DBConnection

The database connection object.

required
vector_id str

The unique identifier of the vector species to search for.

required
lang str

The target language code for localized content.

required
request Request

The FastAPI request object for image URL construction.

required

Returns:

Type Description
list[Disease]

list[Disease]: A list of Disease objects that are transmitted by the specified vector species. Returns an empty list if no diseases are found or if the vector species doesn't exist.

Example

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

Get diseases transmitted by Aedes aegypti

aedes_diseases = get_diseases_by_vector(db, "aedes_aegypti", "en", request) for disease in aedes_diseases: ... print(f"{disease.name} - transmitted by Aedes aegypti")

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/diseases",
        params={"lang": "ru"}
    )
    diseases = response.json()

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