---
title: "Validation Schemas"
description: "Validation schemas are a critical component of the API, serving two primary purposes: ensuring data integrity at runtime and providing clear, machine-readable API specifications for documentation. ..."
last_updated: "2026-05-06T07:29:41.66289+00:00"
canonical_url: "https://www.doc0.dev/docs/49c89830-117b-4def-8edc-b5bcc50766e0/technical/section-4/validation-schemas"
---

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

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

- [apps/api/src/common/pipes/zod-validation.pipe.ts](https://github.com/blade47/comp/blob/main/apps/api/src/common/pipes/zod-validation.pipe.ts)
- [apps/api/src/context/schemas/context-bodies.ts](https://github.com/blade47/comp/blob/main/apps/api/src/context/schemas/context-bodies.ts)
- [apps/api/src/policies/schemas/policy-bodies.ts](https://github.com/blade47/comp/blob/main/apps/api/src/policies/schemas/policy-bodies.ts)
- [apps/api/src/risks/schemas/risk-bodies.ts](https://github.com/blade47/comp/blob/main/apps/api/src/risks/schemas/risk-bodies.ts)
- [apps/api/src/organization/schemas/organization-api-bodies.ts](https://github.com/blade47/comp/blob/main/apps/api/src/organization/schemas/organization-api-bodies.ts)
- [apps/api/src/people/schemas/people-bodies.ts](https://github.com/blade47/comp/blob/main/apps/api/src/people/schemas/people-bodies.ts)
- [apps/api/src/framework-editor/task-template/schemas/task-template-bodies.ts](https://github.com/blade47/comp/blob/main/apps/api/src/framework-editor/task-template/schemas/task-template-bodies.ts)
</details>

Validation schemas are a critical component of the API, serving two primary purposes: ensuring data integrity at runtime and providing clear, machine-readable API specifications for documentation. This system leverages Zod for robust runtime validation within NestJS pipes and `ApiBodyOptions` from `@nestjs/swagger` to generate comprehensive OpenAPI documentation.

This dual approach guarantees that incoming data conforms to expected structures and types, preventing common errors and security vulnerabilities, while simultaneously offering developers an accurate and up-to-date reference for API interactions.

## Zod Validation Pipe

The `ZodValidationPipe` is a custom NestJS `PipeTransform` designed to validate incoming request payloads against a specified Zod schema. This pipe intercepts the request body before it reaches the controller method, ensuring that the data adheres to the defined schema.

### How it Works

1.  **Instantiation**: The pipe is instantiated with a `ZodSchema` object, which defines the expected structure and types of the data.
2.  **Transformation**: The `transform` method receives the incoming `value` (request body) and attempts to parse it using the provided `ZodSchema`.
3.  **Error Handling**: If the `schema.parse()` operation fails (meaning the `value` does not conform to the schema), a `BadRequestException` is thrown, immediately stopping the request processing and returning a 400 Bad Request error to the client. If successful, the parsed (and potentially type-coerced) value is returned.

<Callout variant="info">
This pipe ensures that only valid data structures proceed to the business logic layer, enhancing API reliability and security.
</Callout>

```typescript
import {
  ArgumentMetadata,
  BadRequestException,
  PipeTransform,
} from '@nestjs/common';
import { ZodSchema } from 'zod';

export class ZodValidationPipe implements PipeTransform {
  constructor(private schema: ZodSchema) {}

  transform(value: unknown, metadata: ArgumentMetadata) {
    try {
      const parsedValue = this.schema.parse(value);
      return parsedValue;
    } catch (error) {
      throw new BadRequestException('Validation failed');
    }
  }
}
```
Sources: [apps/api/src/common/pipes/zod-validation.pipe.ts:1-17](https://github.com/blade47/comp/blob/main/apps/api/src/common/pipes/zod-validation.pipe.ts#L1-L17)

### Validation Flow

The following diagram illustrates the data flow through the `ZodValidationPipe`:



## API Body Schemas for Documentation

In addition to runtime validation, the API utilizes `ApiBodyOptions` from `@nestjs/swagger` to define the structure of request bodies for OpenAPI documentation. These schemas are crucial for generating interactive API documentation (e.g., Swagger UI) that clearly outlines expected input formats, types, and examples.

These `ApiBodyOptions` are typically exported as constants in dedicated `*-bodies.ts` files and are referenced in controller methods using the `@ApiBody()` decorator.

### Common Structure

Most API body schemas follow a pattern of defining `ApiBodyOptions` for `create` and `update` operations, often referencing specific Data Transfer Objects (DTOs).

```typescript
import type { ApiBodyOptions } from '@nestjs/swagger';
// ... import DTOs

export const ENTITY_BODIES: Record<string, ApiBodyOptions> = {
  createEntity: {
    description: 'Entity creation data',
    type: CreateEntityDto,
  },
  updateEntity: {
    description: 'Entity update data',
    type: UpdateEntityDto,
  },
};
```

### Detailed Schema Definitions

#### Context Schemas

The `CONTEXT_BODIES` object defines `ApiBodyOptions` for creating and updating context entries, providing detailed examples for Swagger documentation.

```typescript
export const CONTEXT_BODIES: Record<string, ApiBodyOptions> = {
  createContext: {
    description: 'Context entry data',
    type: CreateContextDto,
    examples: {
      'Authentication Context': { /* ... */ },
      'Database Context': { /* ... */ },
    },
  },
  updateContext: {
    description: 'Partial context entry data to update',
    type: UpdateContextDto,
    examples: {
      'Update Tags': { /* ... */ },
      'Update Answer': { /* ... */ },
    },
  },
};
```
Sources: [apps/api/src/context/schemas/context-bodies.ts:4-39](https://github.com/blade47/comp/blob/main/apps/api/src/context/schemas/context-bodies.ts#L4-L39)

#### Policy Schemas

`POLICY_BODIES` defines the expected request bodies for policy creation and updates.

```typescript
export const POLICY_BODIES: Record<string, ApiBodyOptions> = {
  createPolicy: {
    description: 'Policy creation data',
    type: CreatePolicyDto,
  },
  updatePolicy: {
    description: 'Policy update data',
    type: UpdatePolicyDto,
  },
};
```
Sources: [apps/api/src/policies/schemas/policy-bodies.ts:4-13](https://github.com/blade47/comp/blob/main/apps/api/src/policies/schemas/policy-bodies.ts#L4-L13)

#### Risk Schemas

`RISK_BODIES` specifies the request body structures for creating and updating risks.

```typescript
export const RISK_BODIES: Record<string, ApiBodyOptions> = {
  createRisk: {
    description: 'Risk creation data',
    type: CreateRiskDto,
  },
  updateRisk: {
    description: 'Risk update data',
  },
};
```
Sources: [apps/api/src/risks/schemas/risk-bodies.ts:4-13](https://github.com/blade47/comp/blob/main/apps/api/src/risks/schemas/risk-bodies.ts#L4-L13)

#### Organization Schemas

The organization module uses specific `ApiBodyOptions` for updating organization details and transferring ownership. These schemas define properties directly rather than referencing DTOs.

##### `UPDATE_ORGANIZATION_BODY`

| Property            | Type      | Description                               | Example                       |
| :------------------ | :-------- | :---------------------------------------- | :---------------------------- |
| `name`              | `string`  | Organization name                         | `New Acme Corporation`        |
| `slug`              | `string`  | Organization slug                         | `new-acme-corp`               |
| `logo`              | `string`  | Organization logo URL                     | `https://example.com/logo.png`|
| `metadata`          | `string`  | Additional metadata in JSON format        | `{"theme": "dark"}`           |
| `website`           | `string`  | Organization website URL                  | `https://acme-corp.com`       |
| `onboardingCompleted`| `boolean` | Whether onboarding is completed           | `true`                        |
| `hasAccess`         | `boolean` | Whether organization has access to platform| `true`                        |
| `fleetDmLabelId`    | `integer` | FleetDM label ID for device management    | `123`                         |
| `isFleetSetupCompleted`| `boolean` | Whether FleetDM setup is completed        | `false`                       |
| `primaryColor`      | `string`  | Organization primary color in hex format  | `#3B82F6`                     |

Sources: [apps/api/src/organization/schemas/organization-api-bodies.ts:4-58](https://github.com/blade47/comp/blob/main/apps/api/src/organization/schemas/organization-api-bodies.ts#L4-L58)

##### `TRANSFER_OWNERSHIP_BODY`

| Property     | Type      | Description                                                                 | Example             | Required |
| :----------- | :-------- | :-------------------------------------------------------------------------- | :------------------ | :------- |
| `newOwnerId` | `string`  | Member ID of the new owner                                                  | `mem_xyz789`        | Yes      |
| `userId`     | `string`  | User ID of the current owner initiating the transfer (required for API key auth, ignored for JWT auth)| `usr_abc123def456`  | No       |

Sources: [apps/api/src/organization/schemas/organization-api-bodies.ts:60-78](https://github.com/blade47/comp/blob/main/apps/api/src/organization/schemas/organization-api-bodies.ts#L60-L78)

#### People Schemas

`PEOPLE_BODIES` defines schemas for creating single members, bulk creating members, and updating member information.

```typescript
export const PEOPLE_BODIES: Record<string, ApiBodyOptions> = {
  createMember: {
    description: 'Member creation data',
    type: CreatePeopleDto,
  },
  bulkCreateMembers: {
    description: 'Bulk member creation data',
    type: BulkCreatePeopleDto,
  },
  updateMember: {
    description: 'Member update data',
    type: UpdatePeopleDto,
  },
};
```
Sources: [apps/api/src/people/schemas/people-bodies.ts:6-19](https://github.com/blade47/comp/blob/main/apps/api/src/people/schemas/people-bodies.ts#L6-L19)

#### Task Template Schemas

`TASK_TEMPLATE_BODIES` provides the schema for updating task templates within the framework editor.

```typescript
export const TASK_TEMPLATE_BODIES = {
  updateTaskTemplate: {
    type: UpdateTaskTemplateDto,
    description: 'Update framework editor task template data',
  },
};
```
Sources: [apps/api/src/framework-editor/task-template/schemas/task-template-bodies.ts:3-7](https://github.com/blade47/comp/blob/main/apps/api/src/framework-editor/task-template/schemas/task-template-bodies.ts#L3-L7)

### Relationship between ApiBodyOptions and DTOs

`ApiBodyOptions` often reference DTO (Data Transfer Object) classes to describe the expected request body. This provides a clear link between the runtime data structure (defined by the DTO) and its documentation representation.



## Overall API Request Processing with Validation

The following diagram illustrates how validation schemas fit into the broader API request processing pipeline, from client request to response.



## Sitemap

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