Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# DAM Open API Documentation

This directory contains documentation for integrating with the DAM Open API.

## Contents

- [Overview](overview.md) - General overview of the API
- [Authentication](authentication.md) - Authentication methods
- [Endpoints](endpoints.md) - Available API endpoints
- [Integration Examples](integration-examples.md) - Code examples for integration
- [Best Practices](best-practices.md) - Recommended practices for API usage
47 changes: 47 additions & 0 deletions docs/api/authentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Authentication

## Overview

DAM Open API uses HTTP Basic Authentication for securing API access. Authentication is handled through the `BasicAuthWithExclude` provider which extends Drupal's standard Basic Auth.

## Authentication Methods

### Basic Authentication

The API uses standard HTTP Basic Authentication. You need to include an `Authorization` header with each request.

```
Authorization: Basic {base64_encoded_credentials}
```

Where `{base64_encoded_credentials}` is the Base64 encoding of `username:password`.

### Example

```php
$username = 'api_user';
$password = 'api_password';
$auth_header = 'Authorization: Basic ' . base64_encode("$username:$password");
```

## Custom Authentication Provider

DAM Open extends Drupal's Basic Authentication with a custom provider (`BasicAuthWithExclude`) that:

1. Applies authentication only to JSON:API routes
2. Handles LDAP integration for user authentication
3. Provides exclusion mechanisms for specific routes

## Required Permissions

To access the API endpoints, the authenticated user must have the following permission:

- `access tml jsonapi resources`

## Security Best Practices

1. **Use HTTPS**: Always use HTTPS for API communication to encrypt credentials
2. **Dedicated API User**: Create a dedicated user with minimal permissions for API access
3. **Credential Management**: Store API credentials securely and never hardcode them
4. **Token Rotation**: Regularly change API user passwords
5. **IP Restrictions**: Consider restricting API access to specific IP addresses
181 changes: 181 additions & 0 deletions docs/api/best-practices.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
# Best Practices

This document outlines recommended practices for using the DAM Open API effectively and securely.

## Performance Optimization

### Implement Caching

Cache API responses to reduce the number of requests and improve performance:

```php
// Example of simple caching in PHP
function getCachedAssets($base_url, $username, $password, $cache_duration = 3600) {
$cache_file = 'dam_assets_cache.json';
$cache_time = file_exists($cache_file) ? filemtime($cache_file) : 0;

if (time() - $cache_time > $cache_duration) {
// Cache expired or doesn't exist, fetch fresh data
$assets = fetch_dam_assets($base_url, $username, $password);
file_put_contents($cache_file, json_encode($assets));
return $assets;
} else {
// Return cached data
return json_decode(file_get_contents($cache_file), true);
}
}
```

### Use Pagination

When fetching large collections of assets, use pagination to limit the response size:

```
GET /jsonapi/media/image?page[limit]=10&page[offset]=0
```

### Request Only Needed Fields

Specify which fields you need to reduce response size:

```
GET /jsonapi/media/image?fields[media--image]=name,thumbnail,field_category
```

## Security

### Secure Credential Storage

Never hardcode API credentials in your application code. Use environment variables or a secure configuration system:

```php
// PHP example using environment variables
$username = getenv('DAM_API_USERNAME');
$password = getenv('DAM_API_PASSWORD');
```

### Implement Rate Limiting

Implement rate limiting in your application to avoid overwhelming the API:

```php
// Simple rate limiting example
function rateLimitedRequest($endpoint, $headers, $last_request_time, $min_interval = 1) {
$current_time = microtime(true);
if ($current_time - $last_request_time < $min_interval) {
// Sleep to respect rate limit
usleep(($min_interval - ($current_time - $last_request_time)) * 1000000);
}

// Make the request
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);

return [
'response' => $response,
'timestamp' => microtime(true)
];
}
```

### Use HTTPS

Always use HTTPS for API communication to ensure data security.

## Error Handling

### Implement Robust Error Handling

Handle API errors gracefully:

```php
function safeApiRequest($endpoint, $headers) {
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code >= 400) {
// Handle error
return [
'success' => false,
'error' => 'API request failed with code ' . $http_code,
'response' => $response
];
}

return [
'success' => true,
'data' => json_decode($response, true)
];
}
```

### Log API Interactions

Log API interactions for debugging and monitoring:

```php
function logApiRequest($endpoint, $method, $status_code, $response_time) {
$log_entry = date('Y-m-d H:i:s') . " | $method | $endpoint | $status_code | {$response_time}ms\n";
file_put_contents('api_log.txt', $log_entry, FILE_APPEND);
}
```

## Integration Patterns

### Webhook Integration

Consider implementing webhooks to receive updates when assets change:

1. Set up an endpoint in your application to receive webhook notifications
2. Register your webhook URL with the DAM Open system
3. Process incoming webhook notifications to update your local cache

### Batch Processing

For operations involving multiple assets, use batch processing:

```php
function processBatchOfAssets($assets, $operation_callback) {
$results = [];
$batch_size = 10;
$total = count($assets);

for ($i = 0; $i < $total; $i += $batch_size) {
$batch = array_slice($assets, $i, $batch_size);
foreach ($batch as $asset) {
$results[] = $operation_callback($asset);
}
// Add a small delay between batches
usleep(500000); // 500ms
}

return $results;
}
```

## Testing

### Create a Test Environment

Set up a separate test environment for API integration development:

1. Use a separate API user for testing
2. Test with a limited dataset
3. Implement automated tests for your integration

### Monitor API Usage

Monitor your API usage to identify patterns and optimize your integration:

1. Track request frequency
2. Monitor response times
3. Analyze error rates
4. Identify most frequently accessed resources
127 changes: 127 additions & 0 deletions docs/api/endpoints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# API Endpoints

## Media Assets

### Get Media Assets

```
GET /jsonapi/media/image
```

Retrieves a list of media assets of type "image".

**Parameters:**
- `filter[field_name][value]`: Filter by field value
- `page[limit]`: Number of items per page
- `page[offset]`: Offset for pagination
- `sort`: Field to sort by (e.g., `sort=created`)

**Response:**
```json
{
"data": [
{
"type": "media--image",
"id": "uuid",
"attributes": {
"name": "Image Name",
"created": "2023-01-01T12:00:00+00:00",
"changed": "2023-01-01T12:00:00+00:00",
"thumbnail": {
"alt": "Alt text",
"title": "Title text",
"url": "https://example.com/sites/default/files/styles/thumbnail/private/image.jpg"
},
"assets": {
"medium": "https://example.com/sites/default/files/styles/medium/private/image.jpg",
"large": "https://example.com/sites/default/files/styles/large/private/image.jpg"
},
"field_category": ["Category Name"],
"field_keywords": ["Keyword1", "Keyword2"],
"field_gps_gpslatitude": "47.497912",
"field_gps_gpslongitude": "19.040235",
"field_iptc_by_line": "Photographer Name",
"field_iptc_caption": "Image Caption",
"field_iptc_object_name": "Object Name"
}
}
]
}
```

### Get Single Media Asset

```
GET /jsonapi/media/image/{uuid}
```

Retrieves a single media asset by its UUID.

**Response:**
Same structure as above but with a single item.

## File Access

### Get File

```
GET /system/files/{file_path}
```

Retrieves a file by its path.

### Get Private File

```
GET /system/private/file/download/{file_path}
```

Retrieves a private file by its path. Requires authentication.

### Get Image Style

```
GET /image-style/{style}/private/{file_path}
```

Retrieves an image processed with the specified image style.

**Parameters:**
- `style`: The image style to apply (e.g., `thumbnail`, `medium`, `large`)
- `file_path`: Path to the file

## Taxonomy

### Get Categories

```
GET /jsonapi/taxonomy_term/category
```

Retrieves a list of categories.

### Get Keywords

```
GET /jsonapi/taxonomy_term/keywords
```

Retrieves a list of keywords.

## Media Collections

### Get Collections

```
GET /jsonapi/media_collection/media_collection
```

Retrieves a list of media collections.

### Get Collection Items

```
GET /jsonapi/media_collection_item/media_collection_item
```

Retrieves a list of media collection items.
Loading