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

# Get Logistics Requests

> Retrieve a paginated and filterable list of logistics requests for your organization

# Get Logistics Requests

Retrieve logistics requests created by your organization with pagination and filtering support.

<Note>
  **New API**: This endpoint is part of the new API architecture with improved design and maintainability.
</Note>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl --get "https://api.dcycle.io/v1/logistics/requests" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    --data-urlencode "page=1" \
    --data-urlencode "size=50" \
    --data-urlencode "search=MOV-2024" \
    --data-urlencode "trip_date_from=2024-01-01" \
    --data-urlencode "trip_date_until=2024-12-31" \
    --data-urlencode "clients[]=Acme Logistics"
  ```

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

  import requests

  api_key = os.getenv("DCYCLE_API_KEY")
  org_id = os.getenv("DCYCLE_ORG_ID")

  headers = {
      "x-api-key": api_key,
      "x-organization-id": org_id,
  }

  params = [
      ("page", 1),
      ("size", 50),
      ("search", "MOV-2024"),
      ("trip_date_from", "2024-01-01"),
      ("trip_date_until", "2024-12-31"),
      ("clients[]", "Acme Logistics"),
  ]

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

  result = response.json()
  print(f"Total requests: {result['total']}")
  print(f"Page {result['page']} of {max(1, (result['total'] + result['size'] - 1) // result['size'])}")

  for item in result["items"]:
      emissions = item["kgco2e"] if item["kgco2e"] is not None else "pending"
      print(f"- {item['movement_id']}: {item['client']} | {item['origin']} to {item['destination']} | {emissions} kgCO2e")
  ```

  ```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 params = new URLSearchParams({
    page: "1",
    size: "50",
    search: "MOV-2024",
    trip_date_from: "2024-01-01",
    trip_date_until: "2024-12-31"
  });
  params.append("clients[]", "Acme Logistics");

  axios.get("https://api.dcycle.io/v1/logistics/requests", {
    headers: {
      "x-api-key": apiKey,
      "x-organization-id": orgId
    },
    params
  })
  .then(response => {
    const { page, size, total, items } = response.data;
    console.log(`Page ${page} of ${Math.max(1, Math.ceil(total / size))}`);

    items.forEach(item => {
      const emissions = item.kgco2e ?? "pending";
      console.log(`- ${item.movement_id}: ${item.client} | ${item.origin} to ${item.destination} | ${emissions} kgCO2e`);
    });
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "items": [
    {
      "id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
      "movement_id": "MOV-2024-001234",
      "client": "Acme Logistics",
      "shipment_date": "2024-06-15",
      "origin": "Madrid, Spain",
      "destination": "Barcelona, Spain",
      "distance_km": 621.5,
      "load": 1000,
      "load_unit": "kg",
      "toc": "truck_diesel",
      "category": "road",
      "status": "active",
      "kgco2e": 45.2,
      "emission_intensity": 0.0452,
      "created_at": "2024-06-15T09:00:00Z"
    }
  ],
  "total": 1,
  "page": 1,
  "size": 50
}
```

## Use Cases

### List All Logistics Requests

Retrieve every page of logistics requests:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_all_logistics_requests(headers):
    """Retrieve all logistics requests with pagination."""
    all_requests = []
    page = 1

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

        data = response.json()
        all_requests.extend(data["items"])

        if page * data["size"] >= data["total"]:
            break

        page += 1

    return all_requests
```

### Filter by Project and Date

Scope logistics requests to a project and shipment date range:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_project_requests(headers, project_id):
    """Retrieve logistics requests linked to a project for 2024."""
    response = requests.get(
        "https://api.dcycle.io/v1/logistics/requests",
        headers=headers,
        params={
            "page": 1,
            "size": 100,
            "project_id": project_id,
            "trip_date_from": "2024-01-01",
            "trip_date_until": "2024-12-31",
        },
    )
    response.raise_for_status()
    return response.json()
```

### Export to CSV

Export the current filtered page to a CSV file:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import csv


def export_logistics_to_csv(headers, filename="logistics_requests.csv"):
    """Export a page of logistics requests to CSV."""
    response = requests.get(
        "https://api.dcycle.io/v1/logistics/requests",
        headers=headers,
        params={"page": 1, "size": 500, "trip_status": "active"},
    )
    response.raise_for_status()

    data = response.json()
    fields = [
        "id",
        "movement_id",
        "client",
        "shipment_date",
        "origin",
        "destination",
        "distance_km",
        "load",
        "load_unit",
        "toc",
        "status",
        "kgco2e",
        "emission_intensity",
        "created_at",
    ]

    with open(filename, "w", newline="") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fields)
        writer.writeheader()

        for item in data["items"]:
            writer.writerow({field: item.get(field) for field in fields})

    return len(data["items"])
```

## Common Errors

### 401 Unauthorized

**Cause:** Missing or invalid API key

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"detail": "Invalid API key for organization", "code": "INVALID_API_KEY"}
```

### 403 Forbidden

**Cause:** The authenticated user is not a member of the organization

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"detail": "Logged User is not Member of Organization", "code": "LOGGED_USER_NOT_MEMBER"}
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Create Logistics Request" icon="plus" href="/api-reference/logistics/create-request">
    Calculate emissions for a new leg
  </Card>

  <Card title="Get Packages" icon="box" href="/api-reference/logistics/get-packages">
    Retrieve all packages with aggregated emissions
  </Card>

  <Card title="Get Package by ID" icon="box-open" href="/api-reference/logistics/get-package">
    Get a package with all its legs
  </Card>

  <Card title="Get Available Vehicle Types" icon="truck" href="/api-reference/logistics/get-tocs">
    Retrieve all available TOCs
  </Card>

  <Card title="Authentication Guide" icon="key" href="/docs/authentication">
    Learn how to get your API key
  </Card>
</CardGroup>


## OpenAPI

````yaml openapi.json GET /v1/logistics/requests
openapi: 3.0.2
info:
  title: Dcycle API
  description: Local Environment 🏠
  version: 0.0.1
servers: []
security: []
paths:
  /v1/logistics/requests:
    get:
      tags:
        - logistics
      summary: Get Logistics Requests
      description: Get all logistics requests paginated.
      operationId: get_logistics_requests_v1_logistics_requests_get
      parameters:
        - required: false
          schema:
            title: Page
            minimum: 1
            type: integer
            default: 1
          name: page
          in: query
        - required: false
          schema:
            title: Size
            maximum: 500
            minimum: 1
            type: integer
            default: 10
          name: size
          in: query
        - required: false
          schema:
            title: Project Id
            type: string
            format: uuid
          name: project_id
          in: query
        - description: Search across movement ID and stretch ID
          required: false
          schema:
            title: Search
            type: string
            description: Search across movement ID and stretch ID
          name: search
          in: query
        - description: Filter by client name(s)
          required: false
          schema:
            title: Clients[]
            type: array
            items:
              type: string
            description: Filter by client name(s)
          name: clients[]
          in: query
        - description: Filter by trip date >= (YYYY-MM-DD)
          required: false
          schema:
            title: Trip Date From
            type: string
            description: Filter by trip date >= (YYYY-MM-DD)
          name: trip_date_from
          in: query
        - description: Filter by trip date <= (YYYY-MM-DD)
          required: false
          schema:
            title: Trip Date Until
            type: string
            description: Filter by trip date <= (YYYY-MM-DD)
          name: trip_date_until
          in: query
        - description: Filter by vehicle type(s)
          required: false
          schema:
            title: Vehicle Type[]
            type: array
            items:
              type: string
            description: Filter by vehicle type(s)
          name: vehicle_type[]
          in: query
        - description: Filter by trip status
          required: false
          schema:
            title: Trip Status
            type: string
            description: Filter by trip status
          name: trip_status
          in: query
        - description: Filter by uploader user ID(s)
          required: false
          schema:
            title: Uploaded By[]
            type: array
            items:
              type: string
              format: uuid
            description: Filter by uploader user ID(s)
          name: uploaded_by[]
          in: query
        - description: Filter by file ID(s)
          required: false
          schema:
            title: File Id[]
            type: array
            items:
              type: string
              format: uuid
            description: Filter by file ID(s)
          name: file_id[]
          in: query
        - description: Filter by created_at >= (YYYY-MM-DD)
          required: false
          schema:
            title: Created At From
            type: string
            description: Filter by created_at >= (YYYY-MM-DD)
          name: created_at_from
          in: query
        - description: Filter by created_at <= (YYYY-MM-DD)
          required: false
          schema:
            title: Created At To
            type: string
            description: Filter by created_at <= (YYYY-MM-DD)
          name: created_at_to
          in: query
        - required: false
          schema:
            title: X-Api-Key
            type: string
          name: x-api-key
          in: header
        - required: true
          schema:
            title: X-Organization-Id
            type: string
            format: uuid
          name: x-organization-id
          in: header
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetLogisticsRequestsPaginatedOut'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - APIKeyHeader: []
        - OAuth2PasswordBearer: []
components:
  schemas:
    GetLogisticsRequestsPaginatedOut:
      title: GetLogisticsRequestsPaginatedOut
      required:
        - page
        - size
        - total
        - items
      type: object
      properties:
        page:
          title: Page
          type: integer
          description: Current page number
          example: 1
        size:
          title: Size
          type: integer
          description: Number of items per page
          example: 50
        total:
          title: Total
          type: integer
          description: Total number of items
          example: 100
        items:
          title: Items
          type: array
          items:
            $ref: >-
              #/components/schemas/src__app__modules__logistics__schemas__logistics__GetLogisticsRequestOut
          description: List of logistics requests
        filter_hash:
          title: Filter Hash
          type: string
          description: Hash of the applied filters
      description: Response schema for paginated logistics requests.
    HTTPValidationError:
      title: HTTPValidationError
      type: object
      properties:
        detail:
          title: Detail
          type: array
          items:
            $ref: '#/components/schemas/ValidationError'
    src__app__modules__logistics__schemas__logistics__GetLogisticsRequestOut:
      title: GetLogisticsRequestOut
      required:
        - id
        - load_unit
        - created_at
      type: object
      properties:
        id:
          title: Id
          type: string
        origin:
          title: Origin
          type: string
        destination:
          title: Destination
          type: string
        distance_km:
          title: Distance Km
          type: number
        load:
          title: Load
          type: number
        load_unit:
          title: Load Unit
          type: string
        toc:
          title: Toc
          type: string
        cleaning:
          title: Cleaning
          type: boolean
        created_at:
          title: Created At
          type: string
          format: date-time
        status:
          title: Status
          type: string
          default: active
        movement_id:
          title: Movement Id
          type: string
        client:
          title: Client
          type: string
        shipment_date:
          title: Shipment Date
          type: string
          format: date
        movement_stretch:
          title: Movement Stretch
          type: string
        movement_stage:
          title: Movement Stage
          type: string
        vehicle_license_plate:
          title: Vehicle License Plate
          type: string
        trailer_license_plate:
          title: Trailer License Plate
          type: string
        subcontractor:
          title: Subcontractor
          type: boolean
        hub_id:
          title: Hub Id
          type: string
        tkm:
          title: Tkm
          type: number
        kgco2e:
          title: Kgco2E
          type: number
        emission_intensity:
          title: Emission Intensity
          type: number
        error_messages:
          title: Error Messages
          type: array
          items:
            type: string
        estimated_data:
          title: Estimated Data
          type: array
          items:
            type: string
        file_name:
          title: File Name
          type: string
        uploaded_by:
          $ref: '#/components/schemas/UploadedBySch'
        linked_projects:
          title: Linked Projects
          type: array
          items:
            $ref: '#/components/schemas/LinkedProjectSch'
      description: Response schema for a single logistics request.
    ValidationError:
      title: ValidationError
      required:
        - loc
        - msg
        - type
      type: object
      properties:
        loc:
          title: Location
          type: array
          items:
            type: string
        msg:
          title: Message
          type: string
        type:
          title: Error Type
          type: string
    UploadedBySch:
      title: UploadedBySch
      type: object
      properties:
        first_name:
          title: First Name
          type: string
        last_name:
          title: Last Name
          type: string
        profile_img_url:
          title: Profile Img Url
          type: string
      description: User info for uploaded_by field.
    LinkedProjectSch:
      title: LinkedProjectSch
      required:
        - project_id
        - project_name
      type: object
      properties:
        project_id:
          title: Project Id
          type: string
        project_name:
          title: Project Name
          type: string
        project_type:
          $ref: '#/components/schemas/ProjectTypeEnum'
        project_methodology:
          $ref: '#/components/schemas/ProjectMethodologyEnum'
        organization_id:
          title: Organization Id
          type: string
        organization_name:
          title: Organization Name
          type: string
      description: Minimal project info embedded in responses across modules.
    ProjectTypeEnum:
      title: ProjectTypeEnum
      enum:
        - carbon_footprint
        - custom
        - einf
        - iso_14064
        - iso_14001
        - iso_9001
        - lca
        - visualization
        - suppliers
        - logistics
      type: string
      description: Project type.
    ProjectMethodologyEnum:
      title: ProjectMethodologyEnum
      enum:
        - esrs
        - gri
        - glec
        - custom
      type: string
      description: Project methodology.
  securitySchemes:
    APIKeyHeader:
      type: apiKey
      in: header
      name: x-api-key
    OAuth2PasswordBearer:
      type: oauth2
      flows:
        password:
          scopes: {}
          tokenUrl: /v1/auth/login
      x-tokenName: id_token

````