Skip to content

Patient

patient_dto

GetPatientResponse

Bases: BaseModel

DTO for representing the response when getting one or more patients.

Attributes:

Name Type Description
type Optional[str]

The type of response.

message Optional[str]

A message describing the response.

request_resource Optional[Any]

The original request resource.

total_number_of_records Optional[int]

Total number of records.

next_page_link Optional[str]

Link to the next page of results.

Bases: BaseModel

Represents a pagination link in API responses.

Attributes:

Name Type Description
next_page Optional[str]

The link to the next page.

PatientFilterResponse

Bases: BaseModel, Generic[PatientEntry]

A generic response model for filtering patient entries.

This class is designed to handle API responses that return a list of patient-related data along with pagination links and total count.

Attributes:

Name Type Description
entry list[T]

A list of patient entries.

link Optional[Link]

Pagination link information (if available).

total Optional[int]

Total number of patients (if provided).

CreateUpdatePatientResponse

Bases: BaseModel

DTO for representing the response after creating or updating a patient.

Attributes:

Name Type Description
type Optional[str]

The type of response.

message Optional[str]

A message describing the response.

resource_id Optional[str]

The resource ID of the patient.

validation_errors Optional[list[Any]]

List of validation errors, if any.

resource Optional[dict[str, Any]]

The patient resource data.

PatientDTO

Bases: BaseModel

DTO for creating a new patient.

Attributes:

Name Type Description
id_number str

Patient's ID number.

id_type str

Type of ID (must match PatientIdTypeEnum).

abha_address Optional[str]

ABHA address.

patient_type str

Patient type (must match PatientTypeEnum).

first_name str

First name (min 3 chars, only letters and dots).

middle_name Optional[str]

Middle name.

last_name Optional[str]

Last name (min 3 chars, only letters and dots).

birth_date str

Birth date (YYYY-MM-DD).

gender str

Gender (must match Gender enum).

mobile_number Optional[str]

Mobile number (+91 followed by 10 digits).

email_id Optional[str]

Email address.

address str

Address (min 5 chars).

pincode Optional[str]

Pincode (6 digits).

state Optional[str]

State (must match StatesAndUnionTerritories).

wants_to_link_whatsapp Optional[bool]

Whether to link WhatsApp.

photo Optional[str]

Photo.

resource_type str

Resource type (must be 'PATIENT').

resource_id Optional[str]

Resource ID.

UpdatePatientDTO

Bases: BaseModel

DTO for updating an existing patient with specific fields and validations.

Attributes:

Name Type Description
resource_id str

The resource ID of the patient.

email_id Optional[str]

Email address.

mobile_number Optional[str]

Mobile number.

resource_type str

Resource type (must be 'PATIENT').

PatientFiltersDTO

Bases: BaseModel

DTO for filtering patients.

Attributes:

Name Type Description
first_name Optional[str]

First name (min 3 chars, only letters and dots).

last_name Optional[str]

Last name (min 3 chars, only letters and dots).

birth_date Optional[str]

Birth date (YYYY-MM-DD).

gender Optional[str]

Gender (must match Gender enum).

phone Optional[str]

Phone number (+91 followed by 10 digits).

state Optional[str]

State (must match StatesAndUnionTerritories).

organization Optional[str]

Organization name.

count Optional[int]

Number of results to return.

identifier Optional[str]

Identifier string.

BooleanResponse

Bases: BaseModel

Simple boolean response model.

Attributes:

Name Type Description
success bool

Indicates if the operation was successful.

Patient

Patient(config: ClientConfig)

Bases: BaseService

SDK-friendly PatientService for managing patient-related operations.

This service provides methods to interact with patient records in the backend, including creating, updating, deleting, and retrieving patient information. It abstracts the underlying API calls and provides a clean interface for client applications. It also includes advanced filtering capabilities to search for patients based on various criteria.

All data is validated and transformed via Pydantic DTOs ensuring type safety and correct API usage. The service also includes robust logging and error handling for operational reliability.

Key Features

  • Fetch all patients with pagination support.
  • Retrieve patient details by ID.
  • Create new patient records with validation.
  • Update existing patient records.
  • Delete patient records by ID.
  • Advanced filtering capabilities for patient search.

Methods:

Name Description
find_all

Fetches all patients with optional pagination.

find_by_id

Retrieves a patient by their unique ID.

exists

Checks if a patient exists by their ID.

create

Creates a new patient record.

update

Updates an existing patient record.

delete

Deletes a patient record by their ID.

find_by_filters

Retrieves patients based on advanced filters.

Parameters:

Name Type Description Default
config ClientConfig

API credentials and configuration for backend connection.

required
Example Usage
config = ClientConfig(api_key="your_api_key")
patient_service = Patient(config)

# Fetch all patients (first page)
patients = await patient_service.find_all()

# Fetch a specific patient by ID
patient = await patient_service.find_by_id("patient12345")

# Create a new patient
new_patient_data = {
"idNumber": "123456789012",
"idType": "Aadhaar",
"patientType": "OPD",
"firstName": "John",
"lastName": "Doe",
"birthDate": "1980-01-01",
"gender": "M",
"address": "123 Main Street",
"resourceType": "PATIENT"
}
created_patient = await patient_service.create(new_patient_data)

create async

create(patient: dict[str, Any]) -> CreateUpdatePatientResponse

Creates a new patient record in the system.

Parameters:

Name Type Description Default
patient PatientDTO

Data for the new patient to be created.

required

Returns:

Name Type Description
CreateUpdatePatientResponse CreateUpdatePatientResponse

Details about the created patient.

Raises:

Type Description
EhrApiError

For validation failures or backend errors.

Example
new_patient = {
    "idNumber": "123456789012",
    "idType": "Aadhaar",
    "patientType": "OPD",
    "firstName": "Jane",
    "lastName": "Doe",
    "birthDate": "1990-05-10",
    "gender": "F",
    "address": "456 Secondary Rd",
    "resourceType": "PATIENT"
}
created = await patient_service.create(new_patient)
print(created.resource['idNumber'], created.message)
Response:
Sample Output:
{
    "type": "success",
    "message": "Patient created successfully",
    "resourceId": "patient123",
    "resource": {
        "idNumber": "123456789012",
        "firstName": "Jane",
        "lastName": "Doe",
        ...
    },
    "validationErrors": []
}

find_all async

find_all(next_page: Optional[str] = None) -> GetPatientResponse

Retrieves a paginated list of all patients accessible to the current user or organization.

Parameters:

Name Type Description Default
next_page Optional[str]

Token for fetching the next page of results.

None

Returns:

Name Type Description
GetPatientResponse GetPatientResponse

Contains patient entries, pagination info, and metadata.

Raises:

Type Description
EhrApiError

For HTTP or backend errors.

Example
response = await patient_service.find_all()
print(f"Total records: {response.total_records}")
for patient in response.request_resource or []:
    print(patient['idNumber'], patient['firstName'])
Response:
Sample Output:
{
    "type": "success",
    "message": "Patients retrieved successfully",
    "requestResource": [
        {
            "idNumber": "123456789012",
            "firstName": "John",
            "lastName": "Doe",
            ...
        },
        ...
    ],
    "totalNumberOfRecords": 150,
    "nextPage": "token_abc123"
}

find_by_id async

find_by_id(patient_id: str) -> GetPatientResponse

Retrieves detailed information for a patient by their unique ID.

Parameters:

Name Type Description Default
patient_id str

Unique patient identifier.

required

Returns:

Name Type Description
GetPatientResponse GetPatientResponse

Patient detail response object.

Raises:

Type Description
EhrApiError

For invalid ID or API errors.

Example
patient = await patient_service.find_by_id("patient123")
print(patient.request_resource['firstName'], patient.request_resource['lastName'])
Response:
Sample Output:
{
    "type": "success",
    "message": "Patient found",
    "requestResource": {
        "idNumber": "123456789012",
        "firstName": "John",
        "lastName": "Doe",
        "birthDate": "1980-01-01",
        ...
    },
    "totalNumberOfRecords": 1,
    "nextPage": null
}

exists async

exists(patient_id: str) -> bool

Checks whether a patient exists in the registry by patient ID.

Parameters:

Name Type Description Default
patient_id str

Unique ID of the patient.

required

Returns:

Name Type Description
bool bool

True if the patient exists, False otherwise.

Raises:

Type Description
EhrApiError

If there is an error during the API request.

Exception

For unexpected errors during the operation.

Example
exists = await patient_service.exists("patient123")
print("Exists:", exists)
Response:
Sample Output:
True if patient exists, False if not found or error occurs.
False if patient ID is invalid or not found.

update async

update(update_patient_data: dict[str, Any]) -> CreateUpdatePatientResponse

Updates an existing patient record with provided data.

Parameters:

Name Type Description Default
update_patient_data UpdatePatientDTO

Data for updating the patient record.

required

Returns:

Name Type Description
CreateUpdatePatientResponse CreateUpdatePatientResponse

Updated patient details.

Raises:
EhrApiError: For validation or API errors.
Example
update_fields = {
    "resourceId": "patient123",
    "emailId": "jane.doe@example.com",
    "mobileNumber": "+919876543210",
    "resourceType": "PATIENT"
}
updated = await patient_service.update(update_fields)
print(updated.message)
Response:
Sample Output:
{
    "type": "success",
    "message": "Patient updated successfully",
    "resourceId": "patient123",
    "resource": {
        "emailId": "jane.doe@example.com",
        "mobileNumber": "+919876543210",
        ...
    },
    "validationErrors": []
}

delete async

delete(patient_id: str) -> None

Deletes a patient record by their unique ID.

Parameters:

Name Type Description Default
patient_id str

Unique identifier of the patient.

required

Raises:

Type Description
EhrApiError

When ID is invalid or deletion fails.

Example
await patient_service.delete("patient123")
print("Patient deleted successfully.")
Response:
Sample Output:
No content returned on successful deletion.

### Raises:
EhrApiError: If patient ID is invalid or deletion fails.
Exception: Any other unexpected exceptions during deletion.

find_by_filters async

find_by_filters(filters: dict[str, Any], next_page: Optional[str] = None) -> PatientFilterResponse

Retrieves patients based on filter criteria.

Parameters:

Name Type Description Default
filters dict[str, Any]

Filtering criteria.

required
next_page Optional[str]

Pagination token.

None

Returns:

Name Type Description
PatientFilterResponse PatientFilterResponse

Filtered patient data.

Raises:

Type Description
EhrApiError

If there is an error during the API request or validation.