# Application functions

These `azion/applications` functions act on the application itself: the factory that builds a client, the functions that create, list, read, and update an application, the delete, and the methods an application object carries for its sub-resources. Every function takes one object argument.

---

## createAzionApplicationClient

Creates a client that holds a token and exposes the six application-level functions as methods. `createAzionApplicationClient` is also the default export of the module. In TypeScript with `moduleResolution` set to `nodenext`, the default import is not callable, so import the named export. With `moduleResolution` set to `bundler`, both imports type-check.

```typescript
function createAzionApplicationClient(config?: Partial<{
  token: string;
  options?: AzionClientOptions;
}>): AzionApplicationsClient;
```

| Parameter | Type                                                                                               | Required | Description                                                        |
| --------- | -------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------ |
| `token`   | `string`                                                                                           | No       | Your Azion personal token.                                         |
| `options` | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions) | No       | Request options. No sample on this page passes them to the client. |

Returns an [AzionApplicationsClient](/en/documentation/devtools/azion-lib/application/types/#azionapplicationsclient). Its methods take the same object as the matching function on this page. The client has no methods for origins, cache settings, device groups, function instances, or rules: call those functions directly, or use the [application methods](#application-methods).

This sample creates a client and prints its methods:

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

const client = createAzionApplicationClient({
  token: process.env.AZION_TOKEN,
});
console.log('client methods:', Object.keys(client));
```

Output:

```text
client methods: [
  'createApplication',
  'deleteApplication',
  'getApplication',
  'getApplications',
  'putApplication',
  'patchApplication'
]
```

---

## createApplication

Creates an application.

```typescript
function createApplication(params: {
  data: ApiCreateApplicationPayload;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionApplication>>;
```

| Parameter | Type                                                                                                             | Required | Description                                          |
| --------- | ---------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------- |
| `data`    | [`ApiBaseApplicationPayload`](/en/documentation/devtools/azion-lib/application/types/#apibaseapplicationpayload) | Yes      | The settings of the application. `name` is required. |
| `options` | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions)               | No       | Request options.                                     |

Returns `data` as the created [AzionApplication](/en/documentation/devtools/azion-lib/application/types/#azionapplication), with the `id` the API assigned. On an error status, the function throws.

The type declares `application_acceleration`, but API v3 refuses it in a create request as an unknown field. With it, the function throws `Error: HTTP error! Status: 400 - BAD REQUEST`, so leave it out.

This sample is JavaScript, because TypeScript rejects the string `'http,https'` for `delivery_protocol`, whose type is the `DeliveryProtocol` enum:

```javascript
import { createApplication } from 'azion/applications';

// Create a new application
const { data: newApp, error } = await createApplication({
  data: {
    name: 'my-app',
    delivery_protocol: 'http,https',
  },
});
if (newApp) {
  console.log(`Application created: ${newApp.id} (${newApp.name}, ${newApp.delivery_protocol})`);
} else {
  console.error('Error creating application:', error);
}
```

Output:

```text
Application created: 1234567890 (my-app, http,https)
```

---

## getApplications

Lists the applications of the account, one page at a time.

```typescript
function getApplications(params?: {
  params?: ApiListApplicationsParams;
  options?: AzionClientOptions;
}): Promise<AzionApplicationCollectionResponse<AzionApplication>>;
```

| Parameter | Type                                                                                                             | Required | Description                                                                                                                    |
| --------- | ---------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `params`  | [`ApiListApplicationsParams`](/en/documentation/devtools/azion-lib/application/types/#apilistapplicationsparams) | No       | Pagination: `page` and `page_size`. Without ordering keys, the function asks for the list ordered by name, in ascending order. |
| `options` | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions)               | No       | Request options.                                                                                                               |

Returns an [AzionApplicationCollectionResponse](/en/documentation/devtools/azion-lib/application/types/#azionapplicationcollectionresponse): `data.results` holds the page, and `data.count` holds the number of applications in the account. On an error status, the function throws.

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

// List all applications
const { data: apps, error } = await getApplications({
  params: { page: 1, page_size: 20 },
});
if (apps) {
  console.log(`Found ${apps.count} applications; this page has ${apps.results.length}`);
} else {
  console.error('Error listing applications:', error);
}
```

Output:

```text
Found 22 applications; this page has 20
```

---

## getApplication

Returns one application by its ID.

```typescript
function getApplication(params: {
  applicationId: number;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionApplication>>;
```

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

Returns `data` as an [AzionApplication](/en/documentation/devtools/azion-lib/application/types/#azionapplication) that carries the [application methods](#application-methods). An ID that matches no application makes the function throw `Error: HTTP error! Status: 404 - NOT FOUND`.

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

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

const { data: app, error } = await getApplication({ applicationId });

if (error) {
  console.error('Error retrieving application:', error);
} else {
  console.log('Application details:', app?.id, app?.name, app?.delivery_protocol, app?.active);
}
```

Output:

```text
Application details: 1234567890 my-app http,https true
```

---

## patchApplication

Sends the application fields you pass in a `PATCH` request. Use it to rename an application or to change one setting, such as `edge_functions: true`, which [createFunctionInstance](/en/documentation/devtools/azion-lib/application/function-instance/#createfunctioninstance) requires.

```typescript
function patchApplication(params: {
  applicationId: number;
  data: Partial<ApiUpdateApplicationPayload>;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionApplication>>;
```

| Parameter       | Type                                                                                                               | Required | Description                                    |
| --------------- | ------------------------------------------------------------------------------------------------------------------ | -------- | ---------------------------------------------- |
| `applicationId` | `number`                                                                                                           | Yes      | The ID of the application to update.           |
| `data`          | [`ApiUpdateApplicationPayload`](/en/documentation/devtools/azion-lib/application/types/#apibaseapplicationpayload) | 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 [AzionApplication](/en/documentation/devtools/azion-lib/application/types/#azionapplication). On an error status, the function throws.

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

// Update some fields of an existing application
const applicationId = 1234567890; // Replace with the actual application ID

const { data: updatedApp, error } = await patchApplication({
  applicationId,
  data: { name: 'my-app-patched' },
});

if (error) {
  console.error('Error updating application:', error);
} else {
  console.log('Updated application:', updatedApp?.id, updatedApp?.name);
}
```

Output:

```text
Updated application: 1234567890 my-app-patched
```

---

## putApplication

Sends the application settings you pass in a `PUT` request.

```typescript
function putApplication(params: {
  applicationId: number;
  data: ApiUpdateApplicationPayload;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionApplication>>;
```

| Parameter       | Type                                                                                                               | Required | Description                          |
| --------------- | ------------------------------------------------------------------------------------------------------------------ | -------- | ------------------------------------ |
| `applicationId` | `number`                                                                                                           | Yes      | The ID of the application to update. |
| `data`          | [`ApiUpdateApplicationPayload`](/en/documentation/devtools/azion-lib/application/types/#apibaseapplicationpayload) | Yes      | The settings of the application.     |
| `options`       | [`AzionClientOptions`](/en/documentation/devtools/azion-lib/application/types/#azionclientoptions)                 | No       | Request options.                     |

Returns `data` as the updated [AzionApplication](/en/documentation/devtools/azion-lib/application/types/#azionapplication). On an error status, the function throws.

API v3 can refuse a `delivery_protocol` value that the type allows. For example, the API can answer `delivery_protocol: 'https'` with `"https" is not a valid choice.`, and the function then throws.

This sample is JavaScript, because TypeScript rejects the string `'http'` for `delivery_protocol`, whose type is the `DeliveryProtocol` enum:

```javascript
import { putApplication } from 'azion/applications';

// Replace the settings of an existing application
const applicationId = 1234567890; // Replace with the actual application ID

const { data: updatedApp, error } = await putApplication({
  applicationId,
  data: {
    name: 'my-app',
    delivery_protocol: 'http',
  },
});

if (error) {
  console.error('Error updating application:', error);
} else {
  console.log('Updated application:', updatedApp.id, updatedApp.name, updatedApp.delivery_protocol);
}
```

Output:

```text
Updated application: 1234567890 my-app http
```

---

## deleteApplication

Deletes an application by its ID.

```typescript
function deleteApplication(params: {
  applicationId: number;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<void>>;
```

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

Unlike the other application-level functions, `deleteApplication` returns an envelope and does not throw. A successful delete returns `error` with the message `Expected JSON response, but got: `, so the sample confirms the delete with [getApplication](#getapplication), which throws a 404 error for an application that no longer exists.

```typescript
import { deleteApplication, getApplication } from 'azion/applications';

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

const { error: deleteError } = await deleteApplication({ applicationId });

// On success (HTTP 204) the envelope still carries an error, so confirm by reading it back;
// getApplication throws when the application does not exist
try {
  await getApplication({ applicationId });
  console.error('Error deleting application:', deleteError);
} catch (err) {
  console.log(`Application ${applicationId} deleted (read back: ${(err as Error).message})`);
}
```

Output:

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

---

## Application methods

An application that [createApplication](#createapplication) or [getApplication](#getapplication) returns carries the sub-resource functions as methods, already bound to its ID. Each method takes the same object as the matching function, without `applicationId`. The rule methods sit under `rules.request` and `rules.response`, which also fix the `phase`.

| Property                          | Type                    | Methods                                                                                                                     |
| --------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `origins`                         | `OriginOperations`      | `createOrigin`, `getOrigins`, `getOrigin`, `updateOrigin`, `deleteOrigin`                                                   |
| `cache`                           | `CacheOperations`       | `createCacheSetting`, `getCacheSettings`, `getCacheSetting`, `updateCacheSetting`, `deleteCacheSetting`                     |
| `devices`                         | `DeviceGroupOperations` | `createDeviceGroup`, `getDeviceGroups`, `getDeviceGroup`, `updateDeviceGroup`, `deleteDeviceGroup`                          |
| `functions`                       | `FunctionOperations`    | `createFunctionInstance`, `getFunctionInstances`, `getFunctionInstance`, `updateFunctionInstance`, `deleteFunctionInstance` |
| `rules.request`, `rules.response` | `RuleOperations`        | `createRule`, `getRules`, `getRule`, `updateRule`, `deleteRule`                                                             |

A list method needs an object argument, even an empty one: `{}`. This sample reads an application and lists each of its sub-resources through the methods:

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

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

// The application object carries the sub-resource operations, already bound to its ID
const { data: app, error } = await getApplication({ applicationId });
if (!app) throw new Error(error?.message);

const { data: cache } = await app.cache.getCacheSettings({});
console.log('app.cache.getCacheSettings:', cache?.results.map((c) => c.name));
const { data: origins } = await app.origins.getOrigins({});
console.log('app.origins.getOrigins:', origins?.results.map((o) => o.name));
const { data: rules } = await app.rules.request.getRules({});
console.log('app.rules.request.getRules:', rules?.results.map((r) => r.name));
const { data: devices } = await app.devices.getDeviceGroups({});
console.log('app.devices.getDeviceGroups:', devices?.count);
const { data: functions } = await app.functions.getFunctionInstances({});
console.log('app.functions.getFunctionInstances:', functions?.count);
```

Output:

```text
app.cache.getCacheSettings: [ 'my-other-cache-setting' ]
app.origins.getOrigins: [ 'my-origin-updated' ]
app.rules.request.getRules: [ 'Default Rule' ]
app.devices.getDeviceGroups: 0
app.functions.getFunctionInstances: 0
```

---

## 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.
- [Applications | v3](/en/documentation/platform/applications/v3.md): The API v3 application, with its delivery protocols, ports, and settings.
