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

# Rentals

> Learn how to retrieve rental information in the Lightyshare API

Rentals represent the rental transactions in Lightyshare. You can retrieve rental details for rentals where you are either the tenant (renter) or the owner (lender).

## Access Control

Rental information is protected by access control:

* **Tenants**: Can view their own rental details
* **Owners**: Can view rentals of their products
* **Others**: Cannot access rental information

## Retrieving a Rental

### Basic Rental Retrieval

```bash theme={null}
curl -H "Authorization: Bearer YOUR_TOKEN" \
     https://lightyshare.com/api/token-secured/rental/12345
```

### Response Format

```json theme={null}
{
  "rentals": {
    "id": 12345,
    "status": "active",
    "start_date": "2025-01-15",
    "end_date": "2025-01-17",
    "total_amount": 750.00,
    "tenant": {
      "id": 101,
      "name": "John Doe",
      "email": "john@example.com"
    },
    "owner": {
      "id": 202,
      "name": "Jane Smith",
      "email": "jane@example.com"
    },
    "items": [
      {
        "product_id": 1001,
        "title": "4K Pro Camera",
        "quantity": 1,
        "daily_rate": 250.00,
        "total": 500.00
      },
      {
        "product_id": 1002,
        "title": "Professional Tripod",
        "quantity": 1,
        "daily_rate": 50.00,
        "total": 100.00
      }
    ],
    "created_at": "2025-01-10T10:30:00Z",
    "updated_at": "2025-01-10T10:30:00Z"
  }
}
```

## Rental Details

### Core Information

| Field          | Type     | Description                                  |
| -------------- | -------- | -------------------------------------------- |
| `id`           | integer  | Unique rental identifier                     |
| `status`       | string   | Rental status (active, completed, cancelled) |
| `start_date`   | date     | Rental start date                            |
| `end_date`     | date     | Rental end date                              |
| `total_amount` | float    | Total rental cost                            |
| `created_at`   | datetime | Rental creation timestamp                    |
| `updated_at`   | datetime | Last update timestamp                        |

### User Information

| Field    | Type   | Description               |
| -------- | ------ | ------------------------- |
| `tenant` | object | Renter information        |
| `owner`  | object | Product owner information |

### Rental Items

Each rental item includes:

| Field        | Type    | Description              |
| ------------ | ------- | ------------------------ |
| `product_id` | integer | Product identifier       |
| `title`      | string  | Product title            |
| `quantity`   | integer | Number of units rented   |
| `daily_rate` | float   | Daily rental rate        |
| `total`      | float   | Total cost for this item |

## Error Responses

### Unauthorized (401)

```json theme={null}
{
  "error": "Invalid or missing token"
}
```

### Forbidden (403)

```json theme={null}
{
  "error": "Access denied to this resource"
}
```

### Not Found (404)

```json theme={null}
{
  "error": "Resource not found"
}
```

## Use Cases

### For Tenants

* **Track rental history**: View all your past and current rentals
* **Verify rental details**: Confirm dates, items, and costs
* **Contact owners**: Get owner information for communication

### For Owners

* **Monitor rentals**: Track which of your products are currently rented
* **Revenue tracking**: View rental income and history
* **Customer management**: Access tenant information for support

## Best Practices

### 1. Error Handling

Always implement proper error handling for rental requests:

```javascript theme={null}
try {
  const response = await fetch(`/api/token-secured/rental/${rentalId}`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  
  if (response.status === 401) {
    console.error('Authentication failed');
  } else if (response.status === 403) {
    console.error('Access denied to this rental');
  } else if (response.status === 404) {
    console.error('Rental not found');
  } else {
    const rental = await response.json();
    // Process rental data
  }
} catch (error) {
  console.error('Request failed:', error);
}
```

### 2. Data Validation

Validate rental data before processing:

* **Check rental status** before taking actions
* **Verify dates** are in the expected format
* **Confirm amounts** match your expectations

### 3. Security Considerations

* **Never expose rental IDs** in public URLs
* **Validate access permissions** before displaying rental data
* **Sanitize user input** when searching for rentals

## Rental Statuses

### Active

The rental is currently in progress. Items are being used by the tenant.

### Completed

The rental period has ended and items have been returned. The rental is finalized.

### Cancelled

The rental was cancelled before or during the rental period.

## Integration Examples

### Dashboard Integration

```javascript theme={null}
// Fetch user's rentals for dashboard
async function fetchUserRentals(token) {
  const response = await fetch('/api/token-secured/rentals', {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  
  if (response.ok) {
    const rentals = await response.json();
    return rentals.filter(rental => rental.status === 'active');
  }
  
  throw new Error('Failed to fetch rentals');
}
```

### Rental Details Page

```javascript theme={null}
// Display rental details
async function displayRentalDetails(rentalId, token) {
  try {
    const response = await fetch(`/api/token-secured/rental/${rentalId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (response.ok) {
      const { rentals } = await response.json();
      
      // Update UI with rental information
      document.getElementById('rental-title').textContent = `Rental #${rentals.id}`;
      document.getElementById('rental-status').textContent = rentals.status;
      document.getElementById('rental-dates').textContent = 
        `${rentals.start_date} to ${rentals.end_date}`;
      document.getElementById('rental-total').textContent = 
        `$${rentals.total_amount.toFixed(2)}`;
    }
  } catch (error) {
    console.error('Error fetching rental details:', error);
  }
}
```
