Skip to content

Common

Common (atlas.common) is the most structurally important package in Atlas after Core (atlas.core).

It contains general-purpose resources used by higher-level packages, such as model mappings, messaging utilities, pagination, environment metadata, and more.

Below are the descriptions of each resource.

Environment

Environment is a utility class responsible for retrieving environment metadata via static methods.

get_env_vars() staticmethod

Retrieves environment variables stored at AWS Systems Manager Parameter Store, optionally overlaid by local values.

The AWS region comes from AWS_DEFAULT_REGION. The parameter name is read from SSM_ENV_VARS_PARAMETER_NAME when provided by the deployed runtime; during local development, it is derived from APP_NAME using /atlas/<app-name-kebab>/environment. If .atlas/.env.local exists in the current working directory, values declared in that file are applied as a local overlay on top of the SSM values.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: A dictionary containing the merged environment variables, or an empty dictionary if neither SSM nor .atlas/.env.local can provide values.

resolve_ssm_parameter_name(local_env_vars=None) staticmethod

Resolves the environment parameter name configured by CDK or derived from the application name.

Messages

Messages is a centralized, extensible message management utility class used to standardize system messages, logs, and user-facing feedback across multiple languages.

To add custom messages, simply create a class that extends Messages and add your own statements dictionaries to it (e.g. "my_custom_error_statements").

Attributes:

Name Type Description
LANGUAGE str

The current language code used for message retrieval. Determined dynamically from environment variable LANGUAGE. Defaults to en (English) if not explicitly configured.

get(key) classmethod

Retrieves a localized message for the given key.

The method searches for the message in all combined statement sets. If the message exists, it attempts to return it in the currently configured language (as defined by LANGUAGE). If the message for that language does not exist, the English ("en") version is used as a fallback.

Parameters:

Name Type Description Default
key str

The unique identifier of the message.

required

Returns:

Name Type Description
str

The localized message corresponding to the given key.

Raises:

Type Description
KeyError

If the key is not found in any message set, or if the message is missing for both the current language and English.

ModelMapper

ModelMapper is a static utility class responsible for mapping data between two different Python object structures — Pydantic models and SQLAlchemy ORM entities. Each set field contained by the source will be copied to a destination field with same name and compatible type, given it exists.

It enables automatic conversion of complex nested structures, leveraging type hints to recursively instantiate and populate destination objects while maintaining referential integrity when dealing with ORM-managed entities.

This class supports intelligent field mapping, including: - Handling of List and nested model attributes. - Automatic resolution of existing ORM entities by uuid in counterpart Pydantic DTOs. - Selective field assignment for Pydantic DTOs to ignore omitted/non-set fields. - Recursive partial updates for embedded Pydantic models. - Validated construction of new Pydantic destinations by default.

map(src, dst, pydantic_set_fields_only=True, validate_destination=True) staticmethod

Copies attributes from a source object to a destination object, respecting type hints and recursively mapping nested objects and collections.

The mapping process dynamically inspects type annotations from the destination class to determine how to convert each field. Nested objects and lists are recursively mapped using map_instance_to_type().

When both source and destination values are Pydantic models, nested partial DTOs are merged into a copy of the existing embedded model so omitted fields are preserved. Lists are replaced as complete values; Atlas does not infer how list elements should be matched for a merge. Explicit None values still clear nullable fields. Pass pydantic_set_fields_only=False when omitted DTO defaults should participate in a full-value mapping.

validate_destination=True validates nested Pydantic destinations created during mapping. The existing destination keeps assignment semantics so Pydantic models and SQLAlchemy entities can be updated without reconstruction; source annotations should therefore remain compatible with destination field types. Authorization, cross-field invariants, and other business rules belong in domain or service methods.

Parameters:

Name Type Description Default
src Any

The source object (e.g., a DTO, ORM entity, or plain object).

required
dst Any

The destination object whose attributes will be populated.

required
pydantic_set_fields_only bool

If True and src is a Pydantic model, only fields explicitly set in the source will be mapped to the destination. Defaults to True.

True
validate_destination bool

Controls validation of nested Pydantic destinations created during mapping. The existing dst instance itself is updated incrementally and is not reconstructed. Defaults to True.

True

map_instance_to_type(src, dst_type, pydantic_set_fields_only=True, validate_destination=True) staticmethod

Maps a source instance to a new or existing instance of the specified destination type.

If the destination type is an ORM-mapped class (i.e., it defines __table__), and the source object contains a uuid attribute, this method will attempt to retrieve an existing instance from the current session (or from the database, if not present - the most common case). If found, the existing object undergoes a field mapping via map() and gets returned. Otherwise, a NotFoundError is raised.

Parameters:

Name Type Description Default
src Any

The source object to map from (e.g., a Pydantic model or ORM entity).

required
dst_type Type[Any]

The destination class type to map into.

required
pydantic_set_fields_only bool

If True and src is a Pydantic model, only fields explicitly set in the source will be mapped to the destination. Defaults to True.

True
validate_destination bool

If True and dst_type is a Pydantic model, mapped values are passed to its constructor so the destination is validated. Defaults to True. Set to False for permissive, incremental construction compatible with legacy mappings.

True

Returns:

Name Type Description
Any Any

A new or updated instance of dst_type with mapped attributes.

Raises:

Type Description
NotFoundError

If mapping to an ORM entity and no existing instance is found for the given uuid.

map_or_self(src, ret_dto_type, pydantic_set_fields_only=True, validate_destination=True) staticmethod

Maps a source object to a specified destination type if ret_dto_type is provided; otherwise, returns the source object as-is.

Omittable

Bases: Generic[T]

Represents a DTO field (not directly related to any persisted model field) that may have been either omitted or intentionally sent as None in a service method call.

This class is useful to distinguish between the following cases, when it is not possible to trace whether the field was present among the explicitly defined fields (e.g., in Pydantic’s BaseModel.model_fields_set): - A field that was included in the DTO request with a value of None; - A field that was not included (omitted) in the DTO request and was therefore implicitly None.

This distinction is ideal for use in service-layer methods that receive optional parameters derived from DTOs and do not correspond directly to any persisted model field (since for model-bound fields, Optional, default = None, and Pydantic's model_fields_set are sufficient to express nullability and omissibility). It enables correct handling of update operations and conditional logic that depends on the type of absence — whether a value was omitted or explicitly set to None.

An instance can be created manually or from a DTO using Omittable.from_dto.

value property

Returns the underlying field value. May return None, depending on whether the field was explicitly set to None or simply omitted in the DTO.

Returns:

Type Description
Union[T, None]

Union[T, None]: The raw value of the field (may be None).

was_set property

Indicates whether the field was explicitly set (in the DTO or whatever the field's source is).

Returns:

Name Type Description
bool bool

True if the field was set (even if its value is None);
False if the field was omitted.

from_dto(dto, field_name) classmethod

Creates an Omittable instance based on the presence or absence of a field in a given Pydantic DTO.

This method checks whether the target field name is included in dto.model_fields_set. If it is, the field is considered explicitly set (even if its value is None). Otherwise, it is treated as omitted.

Parameters:

Name Type Description Default
dto BaseModel

The Pydantic DTO instance from which to extract field data.

required
field_name str

The name of the field to evaluate.

required

Returns:

Name Type Description
Omittable Omittable

A new instance representing whether the field was present in the DTO and containing its associated value (if provided).

Page

Page is a utility class that represents a single paginated result set, typically used for API responses or repository query results that return partial data from a larger dataset.

It encapsulates both the list of elements for the current page and the associated pagination metadata, such as the current page number, page size, total number of elements, and total pages.

Attributes:

Name Type Description
content List[Any]

The list of items contained in the current page.

page_number int

The index of the current page (starting from 1).

page_size int

The maximum number of elements per page.

total_elements int

The total number of elements across all pages.

total_pages int

The total number of available pages, automatically calculated based on total_elements and page_size.

to_dict()

Converts the current Page instance into a dictionary representation suitable for serialization (e.g., in API responses).

Returns:

Name Type Description
dict

A dictionary containing the following keys: - content: The list of elements in the current page. - page_number: The current page number. - page_size: The configured number of elements per page. - total_pages: The total number of pages. - total_elements: The total count of elements across all pages.

Pageable

Pageable is a helper class responsible for handling pagination and sorting logic in database queries. It defines the paging configuration (page number, page size) and applies sorting dynamically to SQLAlchemy queries.

Attributes:

Name Type Description
DEFAULT_PAGE_NUMBER int

The default page number used when no explicit value is provided. Default is 1.

DEFAULT_PAGE_SIZE int

The default page size used when no explicit value is provided. Default is 20.

page_number int

The current page number to retrieve. Starts from 1.

page_size int

The number of elements to retrieve per page.

sort List[Tuple[str, str]]

The list of sorting criteria as pairs of (field, direction) where direction can be "asc" or "desc".

apply_sort(query, model_class)

Dynamically applies sorting to a SQLAlchemy query based on the sort configuration. Supports sorting by nested relationship fields using dot notation (e.g. "author.name,desc").

Parameters:

Name Type Description Default
query Query

The SQLAlchemy query to which the sorting should be applied.

required
model_class Type

The root SQLAlchemy model corresponding to the query.

required

Returns:

Name Type Description
Query

The updated query with sorting clauses applied.

Raises:

Type Description
ValueError
  • If a field specified in the sort configuration does not exist on the model.
  • If sorting by a collection relationship is attempted (not supported).
  • If the direction is invalid (not "asc" or "desc").

get_offset()

Calculates the offset to apply in SQL queries based on the current page number and size.

Returns:

Name Type Description
int

The offset value, calculated as (page_number - 1) * page_size.

ValidationErrorFormatter

ValidationErrorFormatter is a utility class that provides standardized formatting for Pydantic ValidationError objects, converting low-level Pydantic error codes into human-readable, localized messages defined in the Messages module.

This class maps Pydantic's internal validation error types to custom application-level messages and provides a method to render formatted error strings for API responses or logs.

Attributes:

Name Type Description
_CUSTOM_MESSAGES Dict[str, str]

A dictionary mapping Pydantic error types (e.g., "string_too_short", "value_error") to corresponding localized message templates retrieved from Messages. Each template may contain placeholders such as {loc} and context variables provided by the Pydantic error.

format_errors(ERROR) staticmethod

Formats all errors contained within a Pydantic ValidationError into a list of readable strings.

Parameters:

Name Type Description Default
ERROR ValidationError

The Pydantic ValidationError instance to format.

required

Returns:

Type Description
List[str]

List[str]: A list of formatted error messages, one per field validation error.