> ## 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.

# List Facilities

> Get a paginated list of facilities in your organization

# List Facilities

Retrieve all facilities registered in your organization with pagination support and flexible filtering options.

<Note>
  This endpoint excludes **logistics hubs** from results. Logistics hubs are special facility types used for warehouse and distribution center operations.
</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:** `ff4adcc7-8172-45fe-9cf1-e90a6de53aa9`
</ParamField>

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

  **Example:** `a1b2c3d4-e5f6-7890-abcd-ef1234567890`
</ParamField>

### Query Parameters

<ParamField query="page" type="integer" default="1">
  Page number for pagination

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

<ParamField query="size" type="integer" default="50">
  Number of items per page (max: 100)

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

<ParamField query="name" type="string">
  Filter facilities by name (partial match)

  **Example:** `"Madrid Office"`
</ParamField>

<ParamField query="start_date" type="integer">
  Filter by creation date start (Unix timestamp)

  **Example:** `1704067200` (January 1, 2024)
</ParamField>

<ParamField query="end_date" type="integer">
  Filter by creation date end (Unix timestamp)

  **Example:** `1735689600` (January 1, 2025)
</ParamField>

<ParamField query="filter_by" type="string">
  Advanced filtering criteria (format: `field:value`)

  **Example:** `"country:ES"`
</ParamField>

<ParamField query="sort_by" type="string">
  Sort criteria (format: `field:asc` or `field:desc`)

  **Example:** `"name:asc"`
</ParamField>

## Response

<ResponseField name="page" type="integer">
  Current page number
</ResponseField>

<ResponseField name="size" type="integer">
  Number of items per page
</ResponseField>

<ResponseField name="total" type="integer">
  Total count of **active** facilities (excluding logistics hubs)
</ResponseField>

<ResponseField name="total2" type="integer">
  Total count of **archived** facilities (excluding logistics hubs)
</ResponseField>

<ResponseField name="items" type="array">
  Array of facility objects

  ### Facility Object Fields:

  * `id` (string, UUID) - Unique facility identifier
  * `name` (string) - Facility name
  * `country` (string) - ISO 3166-1 alpha-2 country code
  * `type` (string) - Facility type
  * `address` (string, optional) - Full address
  * `logistic_factor` (float, optional) - Logistic efficiency factor (0.0 - 1.0)
  * `categories` (array of strings, optional) - Facility categories
  * `cups_list` (array of strings, optional) - CUPS codes for electricity meters
  * `status` (string) - `"active"` or `"archived"`
  * `facility_fuels_ids` (array of strings, optional) - Associated fuel IDs
  * `co2e` (float) - Total CO2 equivalent emissions in kg
  * `co2e_biomass` (float, optional) - Biomass CO2 emissions in kg
  * `invoices_length` (integer, optional) - Number of invoices
  * `invoices_in_review_count` (integer) - Number of enabled invoices with `status='review'` for this facility, across all categories (electricity, water, heat, recharge). Defaults to `0`.
  * `created_at` (datetime) - Creation timestamp
  * `updated_at` (datetime) - Last update timestamp
  * `facility_purpose_type` (string) - Purpose classification
  * `supercharger` (boolean, optional) - Electric vehicle supercharger available
  * `facility_id` (string, optional) - External facility identifier
  * `hub_category` (string, optional) - Logistics hub category (null for regular facilities)
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/api/v1/facilities?page=1&size=50&name=Madrid" \
    -H "Authorization: Bearer ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "x-user-id: ${DCYCLE_USER_ID}"
  ```

  ```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")
  user_id = os.getenv("DCYCLE_USER_ID")

  headers = {
      "Authorization": f"Bearer {api_key}",
      "x-organization-id": org_id,
      "x-user-id": user_id
  }

  params = {
      "page": 1,
      "size": 50,
      "name": "Madrid"
  }

  response = requests.get(
      "https://api.dcycle.io/api/v1/facilities",
      headers=headers,
      params=params
  )

  facilities = response.json()
  print(f"Total active facilities: {facilities['total']}")
  print(f"Total archived facilities: {facilities['total2']}")

  for facility in facilities['items']:
      print(f"- {facility['name']} ({facility['country']}): {facility['co2e']} kg CO2e")
  ```

  ```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 userId = process.env.DCYCLE_USER_ID;

  const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'x-organization-id': orgId,
    'x-user-id': userId
  };

  const params = {
    page: 1,
    size: 50,
    name: 'Madrid'
  };

  axios.get('https://api.dcycle.io/api/v1/facilities', { headers, params })
    .then(response => {
      const facilities = response.data;
      console.log(`Total active facilities: ${facilities.total}`);
      console.log(`Total archived facilities: ${facilities.total2}`);

      facilities.items.forEach(facility => {
        console.log(`- ${facility.name} (${facility.country}): ${facility.co2e} kg CO2e`);
      });
    })
    .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "page": 1,
  "size": 50,
  "total": 15,
  "total2": 3,
  "items": [
    {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "name": "Madrid Central Office",
      "country": "ES",
      "type": "office",
      "address": "Calle Gran Vía 123, Madrid, Spain",
      "logistic_factor": 0.8,
      "categories": ["headquarters", "admin"],
      "cups_list": ["ES0031406398765432GH0F"],
      "status": "active",
      "facility_fuels_ids": [],
      "co2e": 12450.5,
      "co2e_biomass": 0.0,
      "invoices_length": 24,
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-11-20T14:22:00Z",
      "facility_purpose_type": "operational",
      "supercharger": true,
      "facility_id": "FAC-2024-001",
      "hub_category": null
    },
    {
      "id": "b2c3d4e5-f6g7-8901-bcde-fg2345678901",
      "name": "Barcelona Production Plant",
      "country": "ES",
      "type": "production",
      "address": "Polígono Industrial Can Salvatella, Barcelona, Spain",
      "logistic_factor": 0.75,
      "categories": ["manufacturing", "production"],
      "cups_list": ["ES0031406398765433AB1G"],
      "status": "active",
      "facility_fuels_ids": ["fuel-id-1", "fuel-id-2"],
      "co2e": 45320.8,
      "co2e_biomass": 1250.0,
      "invoices_length": 48,
      "created_at": "2023-06-10T08:15:00Z",
      "updated_at": "2024-11-18T09:45:00Z",
      "facility_purpose_type": "industrial",
      "supercharger": false,
      "facility_id": "FAC-2023-045",
      "hub_category": null
    }
  ]
}
```

## Common Errors

### 400 Bad Request

**Cause:** Invalid query parameters or date format

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid date format",
  "code": "VALIDATION_ERROR"
}
```

**Solution:** Verify that dates are Unix timestamps (integers) and pagination parameters are positive integers.

### 403 Forbidden

**Cause:** Organization ID doesn't match your API key or user doesn't belong to organization

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Not authorized",
  "code": "FORBIDDEN"
}
```

**Solution:** Verify that `x-organization-id` matches your API key's organization.

## Use Cases

### Facility Dashboard

Display all active facilities with emissions:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_facilities_dashboard():
    """Get facilities for dashboard display"""
    response = requests.get(
        "https://api.dcycle.io/api/v1/facilities",
        headers=headers,
        params={"page": 1, "size": 100, "sort_by": "co2e:desc"}
    )

    facilities = response.json()

    # Calculate totals
    total_emissions = sum(f['co2e'] for f in facilities['items'])

    return {
        'facilities': facilities['items'],
        'total_active': facilities['total'],
        'total_archived': facilities['total2'],
        'total_emissions': total_emissions
    }
```

### Filter by Country

Get all facilities in a specific country:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_facilities_by_country(country_code):
    """Get facilities filtered by country"""
    response = requests.get(
        "https://api.dcycle.io/api/v1/facilities",
        headers=headers,
        params={
            "filter_by": f"country:{country_code}",
            "page": 1,
            "size": 100
        }
    )

    facilities = response.json()

    print(f"Facilities in {country_code}: {facilities['total']}")
    for facility in facilities['items']:
        print(f"  - {facility['name']}: {facility['co2e']:.2f} kg CO2e")

    return facilities

# Example: Get all Spanish facilities
spanish_facilities = get_facilities_by_country("ES")
```

### Date Range Query

Get facilities created within a specific time period:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from datetime import datetime, timedelta

def get_recent_facilities(days=30):
    """Get facilities created in the last N days"""
    end_date = int(datetime.now().timestamp())
    start_date = int((datetime.now() - timedelta(days=days)).timestamp())

    response = requests.get(
        "https://api.dcycle.io/api/v1/facilities",
        headers=headers,
        params={
            "start_date": start_date,
            "end_date": end_date,
            "sort_by": "created_at:desc"
        }
    )

    facilities = response.json()

    print(f"Facilities created in last {days} days: {len(facilities['items'])}")
    return facilities

# Get facilities from last 30 days
recent = get_recent_facilities(30)
```

## Pagination

When you have many facilities, use pagination to retrieve all results:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_all_facilities():
    """Fetch all facilities with pagination"""
    all_facilities = []
    page = 1

    while True:
        response = requests.get(
            "https://api.dcycle.io/api/v1/facilities",
            headers=headers,
            params={"page": page, "size": 100}
        )

        data = response.json()
        all_facilities.extend(data['items'])

        # Check if we've retrieved all items
        if len(all_facilities) >= data['total']:
            break

        page += 1

    return all_facilities

# Get all facilities at once
all_facilities = get_all_facilities()
print(f"Total facilities retrieved: {len(all_facilities)}")
```

## Special Notes

### Logistics Hubs Exclusion

This endpoint automatically excludes logistics hubs from results. Logistics hubs are special facility types with a `hub_category` field set to one of:

* `transshipment_ambient`
* `transshipment_mixed`
* `storage_transhipment_ambient`
* `storage_transhipment_mixed`
* `warehouse_ambient`
* `warehouse_mixed`
* `liquid_bulk_terminals_ambient`
* `liquid_bulk_terminals_mixed`
* `maritime_container_terminals_ambient`
* `maritime_container_terminals_temperature_controlled`

To access logistics hubs, use the dedicated logistics hubs endpoint (if available).

### CO2e Field

The `co2e` field represents the total carbon footprint of the facility calculated from all invoices (electricity, heat, water, etc.). A value of `0.0` means either:

* No invoices have been registered yet
* All invoices have zero emissions
* Calculations are pending

### CUPS Codes

For Spanish facilities, `cups_list` contains electricity meter identifiers (Código Universal del Punto de Suministro). These are automatically populated when creating electricity invoices.

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Create Invoice" icon="file-invoice" href="/api-docs/invoices/create">
    Add consumption data to facilities
  </Card>

  <Card title="List Vehicles" icon="car" href="/api-docs/vehicles/list">
    View your vehicle fleet
  </Card>

  <Card title="Bulk Upload" icon="upload" href="/api-docs/facilities/bulk-upload">
    Upload multiple facilities via CSV
  </Card>

  <Card title="Authentication" icon="key" href="/api-docs/authentication">
    Learn about API authentication
  </Card>
</CardGroup>
