# API Modeling and Semantic Layer in API Cloud: An Explainer for AI Agents

This document explains the API Modeling and Semantic Layer concepts within the `api-cloud` ecosystem. It acts as a companion to the Data Modeling explainer, focusing on how underlying data is exposed, secured, and enriched with business logic.

## 1. API Modeling vs. Data Modeling

While **Data Modeling** (via `DataDomain` and `DomainEntity`) defines the physical or logical structure of the database (tables, columns, foreign keys), **API Modeling** defines the external interface (endpoints, access logic, and authentication) built *on top* of that data.

An `ApiModel` fundamentally requires a dependency on exactly one `DataDomain`. The API model selects a specific subset of data elements to expose, adds security rules, and configures how users authenticate.

## 2. The `ApiModel` Composition

The `ApiModel` class is the root container for API configuration. Key components include:

- **Entity Exposure (`exposes`)**: An array of `ExposedEntity` items mapping to underlying `DomainEntity` objects, determining exactly what is accessible via the API.
- **`user` Entity Reference**: Designates which data entity represents the "User" account in the system (required for publishing).
- **Security & Access**:
  - `authentication`: How users prove their identity (e.g., Username/Password config).
  - `authorization`: What authenticated users are allowed to do (e.g., RBAC).
  - `session`: How the user session is transported (e.g., JWT, Cookies).
  - `accessRule`: API-wide policies that govern exactly who can perform which operations (Create, Read, Update, Delete, List).
- **`rateLimiting`**: API-wide throttling rules to protect from overuse.
- **Metadata**: Contact info, License info, and Terms of Service.

## 3. Exposing Entities (`ExposedEntity`)

Not every table should be a public API endpoint. The `ApiModel` uses the `ExposedEntity` construct to map internal data to RESTful-like paths:

- **Root vs. Nested**: An entity can be exposed as a root resource (e.g., `/users`) or nested via an association (e.g., `/users/{id}/posts`).
- **Paths**: Automatically generates `collectionPath` (e.g., `/users`) and `resourcePath` (e.g., `/users/{id}`) by pluralizing the entity name. Handles collisions by appending incrementing numbers.
- **Recursive Exposure (Following Associations)**: When exposing an entity, the model can traverse its associations up to a `maxDepth` to automatically create nested exposures for related child data.
- **Actions**: While the data entity has properties, the `ExposedEntity` defines "Actions" (operations like typical CRUD or custom RPC-like endpoints) that can be individually secured with their own overridden `accessRule`s.

## 4. The Semantic Layer

The Semantic Layer is a powerful annotation system that bridges the gap between raw data structure and rich, context-aware business logic. It applies rich operational context directly to models so the runtime mechanism knows *how* to handle the data automatically.

### Key Concepts
- **`SemanticType`**: A string enum (e.g., `Semantic#Password`, `Semantic#CreatedTimestamp`, `Semantic#GeospatialCoordinates`) defining the exact meaning of a field or entity.
- **`SemanticScope`**: Where the semantic can be applied:
  - **Entity**: Applies to the whole object (e.g., `User`, `Address`).
  - **Property**: Applies to a specific field (e.g., `Email`, `Password`, `UpdatedTimestamp`).
  - **Association**: Applies to relationships (e.g., `ResourceOwnerIdentifier`, which automatically links a record to the user that created it).

### Execution and Runtime (`SemanticRuntimeConfig`)
Semantics are not just tags; they contain executable instructions for the runtime engine.
- **Timing & Operations**: A semantic defines *when* it runs (`Before`, `After`, `Both`) and for *which operations* (`Create`, `Read`, `Update`, `Delete`, `List`, `Search`).
  - *Example*: `Password` runs `Before` `Create` and `Update` to hash incoming plaintext.
- **Execution Mode**: Runs `Synchronous` (blocking the request), `Asynchronous` (after response), or in the `Background`.
- **Conditions**: JEXL expressions that dynamically evaluate whether a semantic should run. (e.g., `entity[semantics.Password] != null` ensures the password hasher only runs if a new password was provided).
- **Caching & Rate Limiting**: Derived/Computed semantics can configure cache strategies (TTL, Dependency-based) and rate limit specific expensive operations.

### Common Semantic Examples
- **Security**: `Password` (hashes values, hides from responses), `Username` (used for login lookups).
- **Lifecycle**: `CreatedTimestamp`, `UpdatedTimestamp` (auto-populated by runtime), `DeletedFlag` (enables soft-delete behavior).
- **Access Control**: `ResourceOwnerIdentifier` (auto-populates with the authenticated user's ID on creation, and enforces scope so users only see their own records).
- **Rich Data**: `GeospatialCoordinates` (automatically creates spatial db indices and enables distance queries), `Email`, `URL`, `HTML` (triggers sanitization for XSS protection).
