# Respond

Use Respond to stop execution and return a custom HTTP response to the workflow caller.

## Overview

**Type:** `respond`

Set the HTTP status, body, and optional headers. The caller receives the configured body directly, without the normal workflow execution envelope. Keep Respond outside Batch because Batch handles child errors internally.

## Configuration

### Status

* **Type:** Number
* **Required:** No
* **Default:** `200`
* **Min:** `100`
* **Max:** `599`
* **Description:** HTTP status code to return

```
200  // Success
201  // Created
400  // Bad Request
404  // Not Found
500  // Server Error
```

### Body

* **Type:** Object
* **Required:** Yes
* **Templatable:** Yes
* **Description:** Response body (automatically processed with Morpher)

Body fields can contain nested objects, arrays, and template values:

```json
{
  "success": true,
  "data": {
    "userId": "{{ user.id }}",
    "name": "{{ user.name | capitalize }}"
  }
}
```

### Headers

* **Type:** Object (Key-Value pairs)
* **Required:** No
* **Templatable:** Yes
* **Description:** Custom HTTP response headers

```json
{
  "Content-Type": "application/json",
  "X-Request-ID": "{{ requestId }}",
  "X-Processing-Time": "{{ processingTime }}"
}
```

## Behavior

A Respond step in the top-level sequence terminates that sequence. In a Rule or Map, its response also propagates out of the workflow, unless an enclosing Batch captures it. Already started parallel operations continue.

The following sequence is a fragment. Replace `...` with the omitted configuration before execution.

```jsonc
[
  { "type": "request", "output": "data", ... },
  { "type": "respond", ... },  // ← Workflow stops here
  { "type": "email", ... }     // ← This never executes
]
```

## Output

The Respond step does not add data to context. Instead, it returns an HTTP response to the workflow caller.

## Examples

These examples are steps to include in the `steps` array of an [execution request](/docs/execute-workflows). Supply referenced variables such as `currentTimestamp`, `requestId`, and `processingTime` in context; they are not injected automatically.

### Simple success response

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "success": true,
      "message": "Operation completed successfully"
    }
  }
}
```

### Response with dynamic data

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "success": true,
      "data": {
        "id": "{{ user_data.data.id }}",
        "name": "{{ user_data.data.name | capitalize }}",
        "email": "{{ user_data.data.email }}",
        "createdAt": "{{ currentTimestamp }}"
      }
    }
  }
}
```

### Created resource response

```json
{
  "type": "respond",
  "config": {
    "status": 201,
    "body": {
      "success": true,
      "message": "User created successfully",
      "data": {
        "id": "{{ created_user.data.id }}",
        "username": "{{ created_user.data.username }}"
      }
    },
    "headers": {
      "Location": "/users/{{ created_user.data.id }}"
    }
  }
}
```

### Error response - not found

```json
{
  "type": "respond",
  "config": {
    "status": 404,
    "body": {
      "success": false,
      "error": {
        "code": "NOT_FOUND",
        "message": "User not found",
        "details": "No user exists with ID {{ userId }}"
      }
    }
  }
}
```

### Error response - validation error

```json
{
  "type": "respond",
  "config": {
    "status": 400,
    "body": {
      "success": false,
      "error": {
        "code": "VALIDATION_ERROR",
        "message": "Invalid input data",
        "fields": {
          "email": "Invalid email format",
          "age": "Must be at least 18"
        }
      }
    }
  }
}
```

### Conditional responses with Rule

```json
{
  "type": "rule",
  "config": {
    "rules": [
      {
        "conditions": [
          {
            "source": "validation.output.valid",
            "filter": "IS_TRUE"
          }
        ],
        "then": [
          {
            "type": "respond",
            "config": {
              "status": 200,
              "body": {
                "success": true,
                "data": "{{ processedData }}"
              }
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "respond",
            "config": {
              "status": 400,
              "body": {
                "success": false,
                "error": {
                  "code": "VALIDATION_FAILED",
                  "message": "{{ validation.output.errors }}"
                }
              }
            }
          }
        ]
      }
    ]
  }
}
```

### Response with custom headers

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "success": true,
      "data": "{{ results }}"
    },
    "headers": {
      "X-Request-ID": "{{ requestId }}",
      "X-Processing-Time-Ms": "{{ processingTime }}",
      "X-Rate-Limit-Remaining": "{{ rateLimitRemaining }}"
    }
  }
}
```

### Paginated response

Provide `hasNext` as a boolean in context, calculated by your caller or an earlier processing step. Morpher does not evaluate arithmetic or comparisons.

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "success": true,
      "data": "{{ items }}",
      "pagination": {
        "page": "{{ currentPage }}",
        "perPage": "{{ pageSize }}",
        "total": "{{ totalItems }}",
        "hasNext": "{{ hasNext }}"
      }
    }
  }
}
```

### Webhook acknowledgment

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "received": true,
      "webhookId": "{{ webhook.id }}",
      "processedAt": "{{ currentTimestamp }}"
    }
  }
}
```

### AI analysis result

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "success": true,
      "analysis": {
        "sentiment": "{{ sentiment_analysis.output.sentiment }}",
        "score": "{{ sentiment_analysis.output.score }}",
        "categories": "{{ categories.output.categories }}",
        "keywords": "{{ keywords.output.keywords }}"
      },
      "metadata": {
        "modelUsed": "{{ sentiment_analysis.model }}",
        "processingTimeMs": "{{ sentiment_analysis.metadata.duration }}"
      }
    }
  }
}
```

### Batch processing results

This example assumes `processed_items` is an array of records with a boolean `success` field. A Map step returns full iteration contexts, so adjust the field path to your nested output when using Map results.

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "success": true,
      "processed": "{{ processed_items | count }}",
      "results": "{{ processed_items }}",
      "summary": {
        "total": "{{ processed_items | count }}",
        "successful": "{{ processed_items | where('success', true) | count }}",
        "failed": "{{ processed_items | where('success', false) | count }}"
      }
    }
  }
}
```

## Common HTTP status codes

### Success codes (2xx)

* `200` - OK: Standard success response
* `201` - Created: Resource successfully created
* `202` - Accepted: Request accepted for processing
* `204` - No Content: Success with no response body

### Client error codes (4xx)

* `400` - Bad Request: Invalid input or malformed request
* `401` - Unauthorized: Authentication required
* `403` - Forbidden: Insufficient permissions
* `404` - Not Found: Resource does not exist
* `422` - Unprocessable Entity: Validation failed
* `429` - Too Many Requests: Rate limit exceeded

### Server error codes (5xx)

* `500` - Internal Server Error: Unexpected server error
* `502` - Bad Gateway: Upstream service error
* `503` - Service Unavailable: Service temporarily down
* `504` - Gateway Timeout: Upstream timeout

## Best practices

### Response structure consistency

Use a consistent response structure across your API:

```jsonc
// Success format
{
  "success": true,
  "data": { ... },
  "metadata": { ... }
}

// Error format
{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human readable message",
    "details": { ... }
  }
}
```

### Status code selection

* Use appropriate status codes that match the HTTP specification
* `2xx` for successful operations
* `4xx` for client errors (bad input, not found, etc.)
* `5xx` for server errors (unexpected failures)

### Error information

Provide helpful error information:

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Validation failed",
    "fields": {
      "email": "Invalid email format",
      "password": "Password must be at least 8 characters"
    },
    "timestamp": "{{ currentTimestamp }}",
    "requestId": "{{ requestId }}"
  }
}
```

### Security considerations

* Don't expose sensitive internal information in error messages
* Avoid stack traces or system details in production
* Use generic messages for security-related errors
* Sanitize user input before including in responses

### Performance headers

Include useful metadata headers:

```json
{
  "headers": {
    "X-Response-Time": "{{ processingTime }}",
    "X-Rate-Limit-Limit": "1000",
    "X-Rate-Limit-Remaining": "{{ rateLimitRemaining }}",
    "X-Request-ID": "{{ requestId }}"
  }
}
```

## Common use cases

* **API endpoints**: Return structured responses for REST APIs
* **Webhooks**: Acknowledge receipt after any preceding steps complete
* **Validation errors**: Return detailed validation failures early
* **Rate limiting**: Return 429 when limits exceeded
* **Authorization**: Return 401/403 for auth failures
* **Resource creation**: Return 201 with Location header
* **Not found**: Return 404 when resources don't exist
* **Early termination**: Stop processing and respond on certain conditions
* **Error handling**: Return an error for a known condition or a failure captured as data

## Workflow patterns

### Early validation

```jsonc
[
  {
    "type": "rule",
    "config": {
      "rules": [
        {
          "conditions": [{ "source": "input.email", "filter": "NOT_EXISTS" }],
          "then": [
            {
              "type": "respond",
              "config": {
                "status": 400,
                "body": {
                  "success": false,
                  "error": "Email is required",
                },
              },
            },
          ],
        },
      ],
    },
  },
  // Continue with processing...
]
```

### Success after processing

This is an incomplete sequence outline. Replace `...` in the Request and Agent steps with their `config` objects, including the API URL and model settings, before execution.

```json
[
  { "type": "request", "output": "user", ... },
  { "type": "agent", "output": "analysis", ... },
  {
    "type": "respond",
    "config": {
      "status": 200,
      "body": {
        "success": true,
        "user": "{{ user.data }}",
        "analysis": "{{ analysis.output }}"
      }
    }
  }
]
```

### Conditional response

Request rejects HTTP error responses, so this rule runs only after a successful request. Its fallback selects a response for other successful HTTP statuses; it cannot catch a failed request. Use a Batch with `failFast: false` to collect request failures as data.

This is an incomplete sequence outline. Replace the Request step's `...` with its `config` object, and replace both `{...}` placeholders with response bodies before execution.

```json
[
  { "type": "request", "output": "check", ... },
  {
    "type": "rule",
    "config": {
      "rules": [
        {
          "conditions": [
            { "source": "check.status", "filter": "EQUALS", "value": 200 }
          ],
          "then": [
            { "type": "respond", "config": { "status": 200, "body": {...} } }
          ]
        },
        {
          "then": [
            { "type": "respond", "config": { "status": 500, "body": {...} } }
          ]
        }
      ]
    }
  }
]
```

## Troubleshooting

### Templates not resolving

* Verify the context variable path is correct
* Check that previous steps have completed successfully
* Ensure the output name matches what you're referencing
* Use `{{ path }}` and supported helpers. A sole template preserves the value's type; embedded templates produce strings.

### Wrong status code sent

* Verify status code is within valid range (100-599)
* Set a numeric status in configuration; the status field is not templated
* Ensure no other respond steps execute before this one

### Missing response data

* Confirm all referenced context variables exist
* Check that steps producing the data completed
* Verify template paths use correct dot notation

### Headers not applied

* Ensure headers object is properly formatted
* Check for typos in header names
* Verify header values are valid strings
