---
title: "API Architecture"
description: "The API architecture is built upon the NestJS framework, providing a structured and modular approach to developing server-side applications. It serves as the central backend for various functionali..."
last_updated: "2026-05-06T07:29:41.642464+00:00"
canonical_url: "https://www.doc0.dev/docs/49c89830-117b-4def-8edc-b5bcc50766e0/technical/section-2/api-architecture"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [apps/api/src/app.module.ts](https://github.com/blade47/comp/blob/main/apps/api/src/app.module.ts)
- [apps/api/src/main.ts](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts)
- [apps/api/src/app.controller.ts](https://github.com/blade47/comp/blob/main/apps/api/src/app.controller.ts)
- [apps/api/src/app.service.ts](https://github.com/blade47/comp/blob/main/apps/api/src/app.service.ts)
</details>

The API architecture is built upon the NestJS framework, providing a structured and modular approach to developing server-side applications. It serves as the central backend for various functionalities, integrating numerous domain-specific modules, handling requests, and providing a robust and scalable foundation.

The core of the API is defined by its entry point (`main.ts`), which initializes the NestJS application, configures global middleware, security settings, and API documentation. The `AppModule` acts as the root module, orchestrating the integration of various feature modules, configuration settings, and global guards to manage the application's overall behavior.

## Application Entry Point and Bootstrap Process

The `main.ts` file is the primary entry point for the API application. It is responsible for bootstrapping the NestJS application, applying global configurations, setting up middleware, and starting the HTTP server. Before the NestJS application starts, environment variables are loaded to ensure proper configuration.

The `bootstrap` function performs several critical steps:
1.  **Application Creation:** Initializes the NestJS application using `AppModule`.
2.  **CORS Configuration:** Enables Cross-Origin Resource Sharing for all origins, with credentials and exposed headers.
3.  **Security Headers:** Applies `helmet` middleware to set various HTTP security headers, including Content Security Policy (CSP).
4.  **Body Parsing:** Configures `express.json` and `express.urlencoded` to handle request body parsing, with a generous limit of 150MB to accommodate large payloads like base64-encoded attachments.
5.  **Global Pipes:** Registers a `ValidationPipe` globally to enforce data validation, whitelisting, and automatic transformation of incoming data.
6.  **API Versioning:** Enables URI-based API versioning, defaulting to version `1`.
7.  **Swagger/OpenAPI Documentation:** Generates and serves interactive API documentation at `/api/docs`. In development environments, it also writes the OpenAPI specification to a JSON file.
8.  **Server Start:** Listens for incoming HTTP requests on a configured port (defaulting to `3333`).
9.  **Graceful Shutdown:** Implements handlers for `SIGTERM` and `SIGINT` signals to ensure the application closes gracefully.


Sources: [apps/api/src/main.ts:1-93](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts#L1-L93)

## Core Module Structure

The `AppModule` (`app.module.ts`) serves as the root module of the NestJS application. It aggregates all other feature modules, global configurations, and providers, defining the overall structure and dependencies of the API.

### Key Components of `AppModule`

*   **`imports`**: This array lists all the modules that `AppModule` depends on. It includes:
    *   `ConfigModule`: For loading and managing application configurations.
    *   `ThrottlerModule`: Implements rate limiting to protect against abuse.
    *   A comprehensive list of feature modules, each encapsulating specific domain logic (e.g., `AuthModule`, `OrganizationModule`, `DevicesModule`, `TasksModule`, `SOAModule`, `CloudSecurityModule`, etc.).
*   **`controllers`**: Declares `AppController`, which handles basic routes like the root redirect to API documentation.
*   **`providers`**: Registers services and other injectable components, including `AppService` and a global `ThrottlerGuard` for rate limiting.


Sources: [apps/api/src/app.module.ts:1-85](https://github.com/blade47/comp/blob/main/apps/api/src/app.module.ts#L1-L85)

### Configuration Management

The `ConfigModule` is configured globally within `AppModule` to load environment-specific configurations. It uses `awsConfig` and `betterAuthConfig` to provide structured configuration objects throughout the application. The `.env` file is loaded manually in `main.ts` before NestJS initializes, ensuring that environment variables are available for configuration loading.

<Callout variant="info" title="Configuration Loading">
The `ConfigModule` is configured with `isGlobal: true`, making the configuration available across all modules without needing to re-import it. The `load` property specifies configuration factories (`awsConfig`, `betterAuthConfig`) that provide typed configuration objects.
</Callout>

Sources: [apps/api/src/app.module.ts:10-21](https://github.com/blade47/comp/blob/main/apps/api/src/app.module.ts#L10-L21), [apps/api/src/main.ts:1](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts#L1)

## Request Handling Flow

When a request arrives at the API, it passes through a series of middleware, guards, pipes, and controllers before reaching the business logic in services.


Sources: [apps/api/src/main.ts:1-93](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts#L1-L93), [apps/api/src/app.module.ts:22-30](https://github.com/blade47/comp/blob/main/apps/api/src/app.module.ts#L22-L30), [apps/api/src/app.controller.ts:1-12](https://github.com/blade47/comp/blob/main/apps/api/src/app.controller.ts#L1-L12), [apps/api/src/app.service.ts:1-7](https://github.com/blade47/comp/blob/main/apps/api/src/app.service.ts#L1-L7)

### Global Middleware and Guards

The API employs several global mechanisms to ensure security, performance, and data integrity:

*   **CORS:** Enabled for all origins (`origin: true`) to allow client applications to interact with the API.
*   **Helmet:** Configured to add various HTTP security headers, including a Content Security Policy (CSP) that restricts sources for scripts, styles, images, and connections.
*   **Body Parsers:** `express.json` and `express.urlencoded` are used to parse incoming request bodies, with a `150mb` limit to support large data transfers.
*   **ThrottlerGuard:** A global guard provided by `ThrottlerModule` that limits requests to 100 per minute per IP address, preventing abuse and ensuring service availability.

Sources: [apps/api/src/main.ts:18-47](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts#L18-L47), [apps/api/src/app.module.ts:22-30](https://github.com/blade47/comp/blob/main/apps/api/src/app.module.ts#L22-L30)

### Validation Pipe

A global `ValidationPipe` is applied to all incoming requests. This pipe automatically validates incoming data against defined DTOs (Data Transfer Objects), ensuring that requests conform to expected schemas.

<Callout variant="success" title="ValidationPipe Configuration">
The `ValidationPipe` is configured with:
- `whitelist: true`: Removes properties that are not defined in the DTO.
- `forbidNonWhitelisted: true`: Throws an error if non-whitelisted properties are present.
- `transform: true`: Automatically transforms incoming payload objects to DTO instances.
- `transformOptions: { enableImplicitConversion: true }`: Enables implicit type conversion for primitive types.
</Callout>

Sources: [apps/api/src/main.ts:50-59](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts#L50-L59)

## API Versioning

The API supports URI-based versioning, allowing different versions of endpoints to coexist. The default version is `1`.

```typescript
app.enableVersioning({
  type: VersioningType.URI,
  defaultVersion: '1',
});
```
This means endpoints can be accessed like `/v1/resource` or `/v1/another-resource`.
Sources: [apps/api/src/main.ts:61-64](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts#L61-L64)

## API Documentation

The API automatically generates and serves interactive documentation using Swagger (OpenAPI). This documentation is accessible at `/api/docs`.

### Documentation Features

*   **Title and Description:** Provides a clear overview of the API.
*   **Version:** Specifies the API version (`1.0`).
*   **Servers:** Lists available API servers, including local development and production environments.
*   **Authentication:** Supports API key authentication (`X-API-Key` header).
*   **Persistence:** Swagger UI is configured to persist authorization tokens between page refreshes.
*   **Development Output:** In non-production environments, the OpenAPI specification is written to `packages/docs/openapi.json` for external tooling or reference.

Sources: [apps/api/src/main.ts:68-93](https://github.com/blade47/comp/blob/main/apps/api/src/main.ts#L68-L93)

### Root Endpoint Redirect

The root path (`/`) of the API is configured to automatically redirect clients to the Swagger documentation page (`/api/docs`). This redirect is excluded from the generated Swagger documentation itself.

```typescript
@Controller({ version: VERSION_NEUTRAL })
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  @Redirect('/api/docs', 302)
  @ApiExcludeEndpoint()
  redirectToSwagger(): void {
    // This method redirects to Swagger documentation
  }
}
```
Sources: [apps/api/src/app.controller.ts:1-12](https://github.com/blade47/comp/blob/main/apps/api/src/app.controller.ts#L1-L12)

## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/49c89830-117b-4def-8edc-b5bcc50766e0/llms.txt) for all pages in this wiki.
