# OpenAPI Validation Cheatsheet

When defining endpoints in OpenAPI (using JSON Schema–style validation), you can constrain your data in **several** ways. This guide provides a quick overview of **common validation** approaches, such as **string constraints**, **patterns (regex)**, **numerical constraints**, and more.

---

## 1. String Constraints

**OpenAPI** leverages standard JSON Schema properties to validate strings.

### Basic Example

```yaml
components:
  schemas:
    UserName:
      type: string
      description: A simple username
      minLength: 3
      maxLength: 50
```

- **`minLength`**: The string must be at least 3 characters.
- **`maxLength`**: The string must be at most 50 characters.

### Format Examples

- **`format: email`**  
  Validates that a string is an email (e.g., `john@example.com`).
- **`format: uri`**  
  Validates that a string is a URI (e.g., `https://example.com`).
- **`format: date`** / **`format: date-time`**  
  Checks that a string is in a valid date/time format.

```yaml
components:
  schemas:
    Profile:
      type: object
      properties:
        email:
          type: string
          format: email
        website:
          type: string
          format: uri
        birthday:
          type: string
          format: date
      required: [ email, website ]
```

> Note: The `format` checks are not bulletproof but are a quick way to ensure a minimal level of validity.

### Pattern (Regex)

For **custom rules**, add a `"pattern"` (regex). For example:

```yaml
components:
  schemas:
    StrictUserId:
      type: string
      pattern: '^[A-Z0-9]{8}$'
      description: Must be exactly 8 characters of uppercase letters or digits
```
- The pattern `'^[A-Z0-9]{8}$'` enforces exactly 8 uppercase alpha-numerics.

---

## 2. Numeric Constraints

You can validate numbers by specifying **minimum**, **maximum**, and whether the number is an **integer**.

```yaml
components:
  schemas:
    Product:
      type: object
      properties:
        price:
          type: number
          minimum: 0.01
        quantity:
          type: integer
          minimum: 1
          maximum: 9999
      required: [ price, quantity ]
```

- **`type: number`** vs. **`type: integer`**  
  - `number` can have decimals; `integer` cannot.
- **`minimum`** / **`maximum`**  
  - Price must be ≥ 0.01.
  - Quantity must be between 1 and 9999.

---

## 3. Array Constraints

For arrays, use keywords like **items**, **minItems**, and **maxItems**:

```yaml
components:
  schemas:
    TagList:
      type: array
      minItems: 1
      maxItems: 10
      items:
        type: string
        maxLength: 20
```

- **`items`**: schema each array element must follow.
- **`minItems`** / **`maxItems`**: ensures array length constraints.

---

## 4. Required Fields

If you have **object** properties that must be provided:

```yaml
components:
  schemas:
    RegisterUser:
      type: object
      properties:
        username:
          type: string
        password:
          type: string
      required: [ username, password ]
```

Those fields become mandatory. Missing them triggers a **400 Bad Request** from the validator.

---

## 5. Combining Validation Approaches

You can combine multiple validations. For example, ensure a **username** is at least 3 chars and also matches a pattern:

```yaml
components:
  schemas:
    StrictUsername:
      type: string
      minLength: 3
      maxLength: 12
      pattern: '^[a-zA-Z0-9._-]+$'
      description: 3–12 characters, only letters, digits, '.', '_' or '-'
```

---

## 6. How the Validation Happens

- **OpenAPI** spec includes your schemas.
- **Fastify** uses **Ajv** behind the scenes to auto-validate requests.
- If a request body (or query param, path param, etc.) fails to match the schema, a **400** is returned automatically.
- No manual coding needed to check lengths, patterns, or formats—**the schema does the job**.

---

## 7. Quick Tips

1. **Start Simple**  
   Use `type`, `required`, and `format` if that’s all you need.

2. **Regex for Power**  
   `"pattern"` is your friend for custom validations, from strict username rules to domain-specific checks.

3. **Min/Max**  
   Avoid weird input by bounding string length, array length, or numeric ranges.

4. **Keep Schemas Organized**  
   Put them in `components.schemas`. Reuse by referencing them across your OpenAPI spec.

---

## 8. Further Reading

- **Fastify** validation docs: <https://www.fastify.io/docs/latest/Reference/Validation-and-Serialization/>
- **Ajv** official docs: <https://ajv.js.org/>
- **OpenAPI** specification about schema: <https://swagger.io/docs/specification/data-models/data-types/>

