# Rules

A rule belongs to the Rules Engine of an application, in the request phase or the response phase. These `azion/applications` functions create, list, read, update, and delete those rules, and each one takes the phase as `phase`.

---

## createRule

Creates a rule of the Rules Engine of an application, in the request phase or the response phase.

```typescript
function createRule(params: {
  applicationId: number;
  phase: "request" | "response";
  data: ApiCreateRulePayload;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionRule>>;
```

| Parameter       | Type                                                                                                   | Required | Description                                             |
| --------------- | ------------------------------------------------------------------------------------------------------ | -------- | ------------------------------------------------------- |
| `applicationId` | `number`                                                                                               | Yes      | The ID of the application.                              |
| `phase`         | `'request' \| 'response'`                                                                              | Yes      | The phase the rule runs in.                             |
| `data`          | [`ApiCreateRulePayload`](/en/documentation/devtools/azion-lib/application/types/#apicreaterulepayload) | Yes      | The rule: `name`, `phase`, `criteria`, and `behaviors`. |
| `options`       | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions)     | No       | Request options.                                        |

`criteria` is a list of condition groups, and each group is a list of conditions with `variable`, `operator`, `conditional`, and `input_value`. `behaviors` lists the actions, each with a `name` and a `target`. For the variables, operators, and behavior names a rule can use, refer to [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/).

Returns `data` as the created [AzionRule](/en/documentation/devtools/azion-lib/application/types/#azionrule), with its `id` and `order`. In the sample, `as const` keeps the literal types that `phase` and `conditional` need in TypeScript.

```typescript
import { createRule } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID

// Define the data for the new rule
const ruleData = {
  name: 'Example Rule',
  phase: 'request' as const,
  criteria: [[{ variable: '${uri}', operator: 'starts_with', conditional: 'if' as const, input_value: '/example-path' }]],
  behaviors: [{ name: 'redirect_to_301', target: 'https://example.com' }],
};

// Create a new rule in the request phase
const { data: newRule, error } = await createRule({ applicationId, phase: 'request', data: ruleData });

if (error) {
  console.error('Error creating rule:', error);
} else {
  console.log('Created rule:', JSON.stringify(newRule));
}
```

Output:

```text
Created rule: {"id":123457,"name":"Example Rule","phase":"request","behaviors":[{"name":"redirect_to_301","target":"https://example.com"}],"criteria":[[{"variable":"${uri}","operator":"starts_with","conditional":"if","input_value":"/example-path"}]],"is_active":true,"order":1,"description":""}
```

---

## getRules

Lists the rules of one phase of an application, one page at a time.

```typescript
function getRules(params: {
  applicationId: number;
  phase: "request" | "response";
  params?: ApiListRulesParams;
  options?: AzionClientOptions;
}): Promise<AzionApplicationCollectionResponse<AzionRule>>;
```

| Parameter       | Type                                                                                               | Required | Description                         |
| --------------- | -------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- |
| `applicationId` | `number`                                                                                           | Yes      | The ID of the application.          |
| `phase`         | `'request' \| 'response'`                                                                          | Yes      | The phase to list.                  |
| `params`        | [`ApiListRulesParams`](/en/documentation/devtools/azion-lib/application/types/#list-parameters)    | No       | Pagination: `page` and `page_size`. |
| `options`       | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions) | No       | Request options.                    |

Returns an [AzionApplicationCollectionResponse](/en/documentation/devtools/azion-lib/application/types/#azionapplicationcollectionresponse) whose `data.results` holds [AzionRule](/en/documentation/devtools/azion-lib/application/types/#azionrule) objects. The `request` list also holds `Default Rule`, the rule in phase `default` that a new application already has.

```typescript
import { getRules } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID

const { data: rules, error } = await getRules({ applicationId, phase: 'request', params: { page: 1, page_size: 10 } });

if (error) {
  console.error('Error listing rules:', error);
} else {
  console.log(`Found ${rules?.count} rules:`, rules?.results.map((r) => `${r.id} ${r.name} (${r.phase}, order ${r.order})`));
}
```

Output:

```text
Found 2 rules: [
  '123456 Default Rule (default, order 1)',
  '123457 Example Rule (request, order 1)'
]
```

---

## getRule

Returns one rule of an application by its phase and ID.

```typescript
function getRule(params: {
  applicationId: number;
  phase: "request" | "response";
  ruleId: number;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionRule>>;
```

| Parameter       | Type                                                                                               | Required | Description                |
| --------------- | -------------------------------------------------------------------------------------------------- | -------- | -------------------------- |
| `applicationId` | `number`                                                                                           | Yes      | The ID of the application. |
| `phase`         | `'request' \| 'response'`                                                                          | Yes      | The phase of the rule.     |
| `ruleId`        | `number`                                                                                           | Yes      | The ID of the rule.        |
| `options`       | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions) | No       | Request options.           |

Returns `data` as an [AzionRule](/en/documentation/devtools/azion-lib/application/types/#azionrule).

```typescript
import { getRule } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID
const ruleId = 123457; // Replace with the actual rule ID

const { data: rule, error } = await getRule({ applicationId, phase: 'request', ruleId });

if (error) {
  console.error('Error retrieving rule:', error);
} else {
  console.log('Rule details:', JSON.stringify(rule));
}
```

Output:

```text
Rule details: {"id":123457,"name":"Example Rule","phase":"request","behaviors":[{"name":"redirect_to_301","target":"https://example.com"}],"criteria":[[{"variable":"${uri}","operator":"starts_with","conditional":"if","input_value":"/example-path"}]],"is_active":true,"order":1,"description":""}
```

---

## updateRule

Sends the rule fields you pass in a `PATCH` request. Fields you leave out keep their values: a call that does not send `criteria` leaves the `criteria` of the rule unchanged.

```typescript
function updateRule(params: {
  applicationId: number;
  phase: "request" | "response";
  ruleId: number;
  data: ApiUpdateRulePayload;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionRule>>;
```

| Parameter       | Type                                                                                                   | Required | Description                                    |
| --------------- | ------------------------------------------------------------------------------------------------------ | -------- | ---------------------------------------------- |
| `applicationId` | `number`                                                                                               | Yes      | The ID of the application.                     |
| `phase`         | `'request' \| 'response'`                                                                              | Yes      | The phase of the rule.                         |
| `ruleId`        | `number`                                                                                               | Yes      | The ID of the rule to update.                  |
| `data`          | [`ApiUpdateRulePayload`](/en/documentation/devtools/azion-lib/application/types/#apicreaterulepayload) | Yes      | The fields to change. Every field is optional. |
| `options`       | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions)     | No       | Request options.                               |

Returns `data` as the updated [AzionRule](/en/documentation/devtools/azion-lib/application/types/#azionrule).

```typescript
import { updateRule } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID
const ruleId = 123457; // Replace with the actual rule ID

const { data: updatedRule, error } = await updateRule({
  applicationId,
  phase: 'request',
  ruleId,
  data: { name: 'Example Rule Updated', behaviors: [{ name: 'redirect_to_302', target: 'https://example.com/new' }] },
});

if (error) {
  console.error('Error updating rule:', error);
} else {
  console.log('Updated rule:', JSON.stringify(updatedRule));
}
```

Output:

```text
Updated rule: {"id":123457,"name":"Example Rule Updated","phase":"request","behaviors":[{"name":"redirect_to_302","target":"https://example.com/new"}],"criteria":[[{"variable":"${uri}","operator":"starts_with","conditional":"if","input_value":"/example-path"}]],"is_active":true,"order":1,"description":""}
```

---

## deleteRule

Deletes a rule of an application by its phase and ID.

```typescript
function deleteRule(params: {
  applicationId: number;
  phase: "request" | "response";
  ruleId: number;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<void>>;
```

| Parameter       | Type                                                                                               | Required | Description                   |
| --------------- | -------------------------------------------------------------------------------------------------- | -------- | ----------------------------- |
| `applicationId` | `number`                                                                                           | Yes      | The ID of the application.    |
| `phase`         | `'request' \| 'response'`                                                                          | Yes      | The phase of the rule.        |
| `ruleId`        | `number`                                                                                           | Yes      | The ID of the rule to delete. |
| `options`       | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions) | No       | Request options.              |

A successful delete returns `error` with the message `Expected JSON response, but got: `, so the sample reads the rule back with [getRule](#getrule). A `404` error confirms the delete.

```typescript
import { deleteRule, getRule } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID
const ruleId = 123457; // Replace with the actual rule ID

const { error: deleteError } = await deleteRule({ applicationId, phase: 'request', ruleId });

// On success (HTTP 204) the envelope still carries an error, so confirm by reading it back
const { error } = await getRule({ applicationId, phase: 'request', ruleId });
if (error) {
  console.log(`Rule ${ruleId} deleted (read back: ${error.message})`);
} else {
  console.error('Error deleting rule:', deleteError);
}
```

Output:

```text
Rule 123457 deleted (read back: HTTP error! Status: 404 - NOT FOUND)
```

---

## Related resources

- [Azion Lib](/en/documentation/devtools/azion-lib.md): The Azion Lib modules and the npm package each one ships in.
- [Applications](/en/documentation/devtools/azion-lib/application.md): The module's authentication, its response envelope, and the errors its functions report.
- [Application types](/en/documentation/devtools/azion-lib/application/types.md): The payload and response types these functions take and return.
- [Rules Engine](/en/documentation/platform/applications/rules-engine.md): The phases of an application and the criteria and behaviors a rule carries.
