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

# Link Entities by Filters

> Bulk-link all entities matching a filter query to a project in a single operation

# Link Entities by Filters

Link all entities that match a given filter to a project — without needing to enumerate individual IDs. This is the most efficient way to associate large historical datasets or ongoing data streams to a project.

The operation is **idempotent**: entities already linked are skipped, so it is safe to call repeatedly with the same filters.

<Note>
  **New API**: This endpoint is part of the new API architecture.
</Note>

## Request

### Headers

<ParamField header="x-api-key" type="string" required>
  Your API key for authentication

  **Example:** `sk_live_1234567890abcdef`
</ParamField>

<ParamField header="x-organization-id" type="string" required>
  Your organization UUID

  **Example:** `a8315ef3-dd50-43f8-b7ce-d839e68d51fa`
</ParamField>

### Path Parameters

<ParamField path="project_id" type="string" required>
  The UUID of the project to link entities to

  **Example:** `b7f2a1c3-4d5e-6f7a-8b9c-0d1e2f3a4b5c`
</ParamField>

### Body Parameters

<ParamField body="entity_type" type="string" required>
  The type of entities to link. Determines which filter fields are valid.

  **Available values:** `logistic_requests`, `logistic_recharges`, `logistic_packages`, `invoices`, `file_readings`
</ParamField>

<ParamField body="filters" type="object">
  Filter criteria for selecting entities. The valid fields depend on `entity_type` — see the tables below.

  Pass an empty object `{}` to link **all** entities of the given type to the project.
</ParamField>

## Filter Fields by Entity Type

<AccordionGroup>
  <Accordion title="logistic_requests">
    | Field             | Type                  | Description                              |
    | ----------------- | --------------------- | ---------------------------------------- |
    | `search`          | string                | Search across movement ID and stretch ID |
    | `clients`         | array\[string]        | Filter by client name(s)                 |
    | `trip_date_from`  | string (YYYY-MM-DD)   | Filter by trip date >=                   |
    | `trip_date_until` | string (YYYY-MM-DD)   | Filter by trip date \<=                  |
    | `vehicle_type`    | array\[string]        | Filter by vehicle type(s)                |
    | `uploaded_by`     | array\[string (UUID)] | Filter by uploader user ID(s)            |
    | `file_id`         | array\[string (UUID)] | Filter by source file ID(s)              |
    | `created_at_from` | string (YYYY-MM-DD)   | Filter by creation date >=               |
    | `created_at_to`   | string (YYYY-MM-DD)   | Filter by creation date \<=              |

    <Warning>
      Unknown filter keys return a `422` error. Only the fields listed above are accepted.
    </Warning>
  </Accordion>

  <Accordion title="logistic_recharges">
    | Field                   | Type                  | Description                 |
    | ----------------------- | --------------------- | --------------------------- |
    | `vehicle_type`          | array\[string]        | Filter by vehicle type(s)   |
    | `fuel_id`               | array\[string (UUID)] | Filter by fuel ID(s)        |
    | `vehicle_license_plate` | array\[string]        | Filter by license plate(s)  |
    | `file_id`               | array\[string (UUID)] | Filter by source file ID(s) |
    | `date_from`             | string (YYYY-MM-DD)   | Filter by recharge date >=  |
    | `date_until`            | string (YYYY-MM-DD)   | Filter by recharge date \<= |
    | `created_at_from`       | string (YYYY-MM-DD)   | Filter by creation date >=  |
    | `created_at_to`         | string (YYYY-MM-DD)   | Filter by creation date \<= |
  </Accordion>

  <Accordion title="logistic_packages">
    | Field             | Type                | Description                 |
    | ----------------- | ------------------- | --------------------------- |
    | `created_at_from` | string (YYYY-MM-DD) | Filter by creation date >=  |
    | `created_at_to`   | string (YYYY-MM-DD) | Filter by creation date \<= |
  </Accordion>

  <Accordion title="invoices">
    | Field          | Type                  | Description                  |
    | -------------- | --------------------- | ---------------------------- |
    | `types`        | array\[string]        | Filter by invoice type(s)    |
    | `statuses`     | array\[string]        | Filter by invoice status(es) |
    | `facility_ids` | array\[string (UUID)] | Filter by facility ID(s)     |
    | `start_date`   | string (YYYY-MM-DD)   | Filter by invoice date >=    |
    | `end_date`     | string (YYYY-MM-DD)   | Filter by invoice date \<=   |
  </Accordion>

  <Accordion title="file_readings">
    | Field    | Type    | Description                                                             |
    | -------- | ------- | ----------------------------------------------------------------------- |
    | `linked` | boolean | `true` = only already-linked readings; `false` = only unlinked readings |
  </Accordion>
</AccordionGroup>

## Response

<ResponseField name="created" type="integer">
  Number of new links created
</ResponseField>

<ResponseField name="skipped" type="integer">
  Number of entities that were already linked (skipped)
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL — logistics requests by date range theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X POST "https://api.dcycle.io/v1/projects/b7f2a1c3-4d5e-6f7a-8b9c-0d1e2f3a4b5c/entities/link-by-filters" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "Content-Type: application/json" \
    -d '{
      "entity_type": "logistic_requests",
      "filters": {
        "trip_date_from": "2024-01-01",
        "trip_date_until": "2024-03-31",
        "clients": ["AMAZON"]
      }
    }'
  ```

  ```bash cURL — all invoices from a facility theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X POST "https://api.dcycle.io/v1/projects/b7f2a1c3-4d5e-6f7a-8b9c-0d1e2f3a4b5c/entities/link-by-filters" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "Content-Type: application/json" \
    -d '{
      "entity_type": "invoices",
      "filters": {
        "facility_ids": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"],
        "start_date": "2024-01-01",
        "end_date": "2024-12-31"
      }
    }'
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests
  import os

  api_key = os.getenv("DCYCLE_API_KEY")
  org_id = os.getenv("DCYCLE_ORG_ID")
  project_id = "b7f2a1c3-4d5e-6f7a-8b9c-0d1e2f3a4b5c"

  headers = {
      "x-api-key": api_key,
      "x-organization-id": org_id,
      "Content-Type": "application/json"
  }

  # Link all logistics requests for Q1 2024 from a specific client
  payload = {
      "entity_type": "logistic_requests",
      "filters": {
          "trip_date_from": "2024-01-01",
          "trip_date_until": "2024-03-31",
          "clients": ["AMAZON"]
      }
  }

  response = requests.post(
      f"https://api.dcycle.io/v1/projects/{project_id}/entities/link-by-filters",
      headers=headers,
      json=payload
  )

  result = response.json()
  print(f"Created: {result['created']}, Skipped (already linked): {result['skipped']}")
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const axios = require('axios');

  const apiKey = process.env.DCYCLE_API_KEY;
  const orgId = process.env.DCYCLE_ORG_ID;
  const projectId = 'b7f2a1c3-4d5e-6f7a-8b9c-0d1e2f3a4b5c';

  const headers = {
    'x-api-key': apiKey,
    'x-organization-id': orgId,
    'Content-Type': 'application/json'
  };

  // Link all fuel recharges for a specific vehicle type
  const payload = {
    entity_type: 'logistic_recharges',
    filters: {
      vehicle_type: ['van_diesel'],
      date_from: '2024-01-01',
      date_until: '2024-12-31'
    }
  };

  axios.post(
    `https://api.dcycle.io/v1/projects/${projectId}/entities/link-by-filters`,
    payload,
    { headers }
  )
  .then(response => {
    console.log(`Created: ${response.data.created}, Skipped: ${response.data.skipped}`);
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "created": 347,
  "skipped": 12
}
```

## Common Errors

### 404 Not Found

**Cause:** Project not found or doesn't belong to your organization

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "code": "NOT_FOUND",
  "detail": "Project not found"
}
```

### 422 Invalid Filters

**Cause:** An unknown filter key was passed for the given `entity_type`

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "code": "INVALID_FILTERS",
  "detail": "Unknown filter key: 'foo'"
}
```

**Solution:** Check the filter fields table for your `entity_type` above. Only the listed fields are accepted — extra keys are rejected.

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Link Entities" icon="link" href="/api-reference/projects/link-entities">
    Link specific entities by ID
  </Card>

  <Card title="Unlink Entities" icon="link-slash" href="/api-reference/projects/unlink-entities">
    Remove entity-project associations
  </Card>
</CardGroup>
