> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mudstack.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Update status on assets

## Introduction

Managing asset statuses efficiently is a common requirement in workflows involving digital asset management systems. This guide demonstrates how to automate the process of searching for assets, filtering them based on their last update date, retrieving available statuses, and updating the status of selected assets. By following these examples, you can streamline your asset management tasks and integrate them into your existing workflows.

Authentication is a critical step in interacting with the Mudstack API. Each request requires an authorization token, which is obtained using your API key and secret. Additionally, the `x-workspace-id` and `x-account-id` headers must be included in every request to ensure proper scoping.

This example is particularly useful for scenarios such as:

* Keeping track of assets that require immediate attention.
* Automating status updates for assets based on predefined criteria.
* Integrating asset management with other systems or workflows.

This example demonstrates how to:

1. Authenticate and retrieve an authorization token.
2. Search for assets in a specific path using the [`/workspaces/assets/search`](../workspaces/assets/search-assets) endpoint.
3. Filter out assets that are more than 2 weeks old.
4. Retrieve all asset statuses using the [`/workspaces/assetStatuses`](../workspaces/assets/status/get-statuses) endpoint and find the status with the name "In Progress".
5. Assign the `status_id` of the "In Progress" status to each filtered asset and update them using the [`/workspaces/assets/{asset_id}`](../workspaces/assets/update-asset) endpoint.

## Steps

### Step 1: Authenticate and Retrieve an Authorization Token

Use the [`/auth/token`](../auth/authenticate-api-key) endpoint to retrieve an authorization token. Replace `<your_account_id>`, `<your_key>`, and `<your_secret>` with your account ID, API key, and secret, respectively.

<CodeGroup>
  ```python auth.py theme={null}
  # Python example to retrieve an authorization token
  import requests

  url = "https://api.mudstack.com/auth/token"
  headers = {
      "x-account-id": "<your_account_id>",
      "Content-Type": "application/json"
  }
  data = {
      "key": "<your_key>",
      "secret": "<your_secret>"
  }
  response = requests.post(url, headers=headers, json=data)
  token = response.json()["token"]
  print(token)
  ```

  ```javascript auth.js theme={null}
  // JavaScript example to retrieve an authorization token
  const fetch = require('node-fetch');

  const url = "https://api.mudstack.com/auth/token";
  const headers = {
      "x-account-id": "<your_account_id>",
      "Content-Type": "application/json"
  };
  const data = {
      key: "<your_key>",
      secret: "<your_secret>"
  };

  fetch(url, { method: "POST", headers, body: JSON.stringify(data) })
      .then(res => res.json())
      .then(data => console.log(data.token));
  ```

  ```csharp auth.cs theme={null}
  // C# example to retrieve an authorization token
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;

  class Program {
      static async Task Main(string[] args) {
          var client = new HttpClient();
          var requestBody = "{\"key\": \"<your_key>\", \"secret\": \"<your_secret>\"}";
          var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
          content.Headers.Add("x-account-id", "<your_account_id>");
          var response = await client.PostAsync("https://api.mudstack.com/auth/token", content);
          var token = await response.Content.ReadAsStringAsync();
          Console.WriteLine(token);
      }
  }
  ```
</CodeGroup>

### Step 2: Search for Assets in a Specific Path

Use the [`/workspaces/assets/search`](../workspaces/assets/search-assets) endpoint to search for assets in a specific path. Replace `<your_token>`, `<workspace_id>`, and `<account_id>` with your authorization token, workspace ID, and account ID, respectively.

<CodeGroup>
  ```python search-assets.py theme={null}
  # Python example to search for assets
  import requests

  url = "https://api.mudstack.com/workspaces/assets/search"
  headers = {
      "Authorization": "Bearer <your_token>",
      "x-workspace-id": "<workspace_id>",
      "x-account-id": "<account_id>",
      "Content-Type": "application/json"
  }
  data = {"folder": "/example/path"}
  response = requests.get(url, headers=headers, json=data)
  print(response.json())
  ```

  ```javascript search-assets.js theme={null}
  // JavaScript example to search for assets
  const fetch = require('node-fetch');

  const url = "https://api.mudstack.com/workspaces/assets/search";
  const headers = {
      "Authorization": "Bearer <your_token>",
      "x-workspace-id": "<workspace_id>",
      "x-account-id": "<account_id>",
      "Content-Type": "application/json"
  };
  const data = { folder: "/example/path" };

  fetch(url, { method: "GET", headers, body: JSON.stringify(data) })
      .then(res => res.json())
      .then(console.log);
  ```

  ```csharp search-assets.cs theme={null}
  // C# example to search for assets
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;

  class Program {
      static async Task Main(string[] args) {
          var client = new HttpClient();
          var request = new HttpRequestMessage(HttpMethod.Get, "https://api.mudstack.com/workspaces/assets/search");
          request.Headers.Add("Authorization", "Bearer <your_token>");
          request.Headers.Add("x-workspace-id", "<workspace_id>");
          request.Headers.Add("x-account-id", "<account_id>");
          request.Content = new StringContent("{\"folder\": \"/example/path\"}", Encoding.UTF8, "application/json");

          var response = await client.SendAsync(request);
          Console.WriteLine(await response.Content.ReadAsStringAsync());
      }
  }
  ```
</CodeGroup>

**Response Example:**

```json theme={null}
{
  "assets": [
    {
      "id": "asset1",
      "name": "file1.png",
      "updated_at": "2023-10-01T12:00:00Z"
    },
    {
      "id": "asset2",
      "name": "file2.png",
      "updated_at": "2023-09-15T12:00:00Z"
    }
  ]
}
```

### Step 3: Filter Assets Older Than 2 Weeks

Filter the assets by comparing the `updated_at` field to the current date. This ensures only assets updated within the last 2 weeks are processed.

<CodeGroup>
  ```python filter-assets.py theme={null}
  # Python example to filter assets
  from datetime import datetime, timedelta

  two_weeks_ago = datetime.now() - timedelta(days=14)
  filtered_assets = [asset for asset in assets if datetime.fromisoformat(asset['updated_at']) > two_weeks_ago]
  ```

  ```javascript filter-assets.js theme={null}
  // Filter assets updated within the last 2 weeks
  const twoWeeksAgo = new Date();
  twoWeeksAgo.setDate(twoWeeksAgo.getDate() - 14);

  const filteredAssets = assets.filter(asset => new Date(asset.updated_at) > twoWeeksAgo);
  ```

  ```csharp filter-assets.cs theme={null}
  // C# example to filter assets
  using System;
  using System.Collections.Generic;

  class Program {
      static void Main(string[] args) {
          List<Asset> assets = new List<Asset>();
          // Add assets to the list

          DateTime twoWeeksAgo = DateTime.Now.AddDays(-14);
          List<Asset> filteredAssets = assets.FindAll(asset => DateTime.Parse(asset.UpdatedAt) > twoWeeksAgo);
      }
  }

  class Asset {
      public string Id { get; set; }
      public string Name { get; set; }
      public string UpdatedAt { get; set; }
  }
  ```
</CodeGroup>

### Step 4: Retrieve Asset Statuses and Find "In Progress"

Use the [`/workspaces/assetStatuses`](../workspaces/assets/status/get-statuses) endpoint to retrieve all asset statuses. Identify the status with the name "In Progress".

<CodeGroup>
  ```python retrieve-statuses.py theme={null}
  # Python example to retrieve statuses
  import requests

  url = "https://api.mudstack.com/workspaces/assetStatuses"
  headers = {
      "Authorization": "Bearer <your_token>",
      "x-workspace-id": "<workspace_id>",
      "x-account-id": "<account_id>"
  }
  response = requests.get(url, headers=headers)
  statuses = response.json()["statuses"]
  in_progress_status = next(status for status in statuses if status["name"] == "In Progress")
  print(in_progress_status)
  ```

  ```javascript retrieve-statuses.js theme={null}
  // JavaScript example to retrieve statuses
  const fetch = require('node-fetch');

  const url = "https://api.mudstack.com/workspaces/assetStatuses";
  const headers = {
      "Authorization": "Bearer <your_token>",
      "x-workspace-id": "<workspace_id>",
      "x-account-id": "<account_id>"
  };

  fetch(url, { method: "GET", headers })
      .then(res => res.json())
      .then(data => {
          const inProgressStatus = data.statuses.find(status => status.name === "In Progress");
          console.log(inProgressStatus);
      });
  ```

  ```csharp retrieve-statuses.cs theme={null}
  // C# example to retrieve statuses
  using System;
  using System.Net.Http;
  using System.Threading.Tasks;
  using Newtonsoft.Json.Linq;

  class Program {
      static async Task Main(string[] args) {
          var client = new HttpClient();
          var request = new HttpRequestMessage(HttpMethod.Get, "https://api.mudstack.com/workspaces/assetStatuses");
          request.Headers.Add("Authorization", "Bearer <your_token>");
          request.Headers.Add("x-workspace-id", "<workspace_id>");
          request.Headers.Add("x-account-id", "<account_id>");

          var response = await client.SendAsync(request);
          var jsonResponse = await response.Content.ReadAsStringAsync();
          var statuses = JObject.Parse(jsonResponse)["statuses"];
          var inProgressStatus = statuses.First(status => status["name"].ToString() == "In Progress");
          Console.WriteLine(inProgressStatus);
      }
  }
  ```
</CodeGroup>

**Response Example:**

```json theme={null}
{
  "statuses": [
    {
      "id": "status1",
      "name": "In Progress",
      "color": "#FFCC00"
    },
    {
      "id": "status2",
      "name": "Completed",
      "color": "#00FF00"
    }
  ]
}
```

### Step 5: Update Assets with the "In Progress" Status

For each filtered asset, assign the `status_id` of the "In Progress" status and update the asset using the [`/workspaces/assets/{asset_id}`](../workspaces/assets/update-asset) endpoint.

<CodeGroup>
  ```python update-assets.py theme={null}
  # Python example to update assets
  import requests

  url_template = "https://api.mudstack.com/workspaces/assets/{asset_id}"
  headers = {
      "Authorization": "Bearer <your_token>",
      "x-workspace-id": "<workspace_id>",
      "x-account-id": "<account_id>",
      "Content-Type": "application/json"
  }

  for asset in filtered_assets:
      url = url_template.format(asset_id=asset["id"])
      data = {"status_id": in_progress_status["id"]}
      response = requests.patch(url, headers=headers, json=data)
      print(f"Updated asset {asset['id']}: {response.status_code}")
  ```

  ```javascript update-assets.js theme={null}
  // JavaScript example to update assets
  const fetch = require('node-fetch');

  const urlTemplate = "https://api.mudstack.com/workspaces/assets/{asset_id}";
  const headers = {
      "Authorization": "Bearer <your_token>",
      "x-workspace-id": "<workspace_id>",
      "x-account-id": "<account_id>",
      "Content-Type": "application/json"
  };

  filteredAssets.forEach(asset => {
      const url = urlTemplate.replace("{asset_id}", asset.id);
      const data = { status_id: inProgressStatus.id };

      fetch(url, { method: "PATCH", headers, body: JSON.stringify(data) })
          .then(res => console.log(`Updated asset ${asset.id}: ${res.status}`))
          .catch(console.error);
  });
  ```

  ```csharp update-assets.cs theme={null}
  // C# example to update assets
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;

  class Program {
      static async Task Main(string[] args) {
          var client = new HttpClient();
          string urlTemplate = "https://api.mudstack.com/workspaces/assets/{asset_id}";

          foreach (var asset in filteredAssets) {
              string url = urlTemplate.Replace("{asset_id}", asset.Id);
              string requestBody = $"{{\"status_id\": \"{inProgressStatus.Id}\"}}";

              var request = new HttpRequestMessage(HttpMethod.Patch, url);
              request.Headers.Add("Authorization", "Bearer <your_token>");
              request.Headers.Add("x-workspace-id", "<workspace_id>");
              request.Headers.Add("x-account-id", "<account_id>");
              request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

              var response = await client.SendAsync(request);
              Console.WriteLine($"Updated asset {asset.Id}: {response.StatusCode}");
          }
      }
  }
  ```
</CodeGroup>

**Response Example:**

```json theme={null}
{
  "id": "<asset_id>",
  "status_id": "<status_id>"
}
```

***

## Explore More Examples

Looking for more examples? Check out the following guides to learn about other use cases:

* [Search Assets](../examples/searching-assets)
* [Invite Users to Account](../examples/invite-users-to-account)
* [Get Assets with Outstanding Tasks](../examples/get-assets-with-outstanding-tasks)
