Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Dropbox Api Laravel Package

spatie/dropbox-api

Minimal PHP client for Dropbox API v2 by Spatie. Provides core endpoints used by their Flysystem Dropbox adapter—create folders, list directories, fetch temporary links, and more. Easy to install via Composer and use with an auth token.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require spatie/dropbox-api
  1. Obtain a Dropbox API token:

    • Generate an access token from the Dropbox App Console.
    • For OAuth2 flows, use a library like league/oauth2-client to handle token refreshes.
  2. Initialize the client:

    use Spatie\Dropbox\Client;
    
    $client = new Client($accessToken);
    

First Use Case: Upload a File

$client->upload('/path/to/file.txt', file_get_contents('local-file.txt'));

First Use Case: List Folder Contents

$contents = $client->listFolder('/dropbox-folder-path');
foreach ($contents as $item) {
    echo $item['name'] . "\n";
}

First Use Case: Generate a Shared Link

$link = $client->getTemporaryLink('/path/to/file.txt');

Implementation Patterns

Core Workflows

File Management

  • Upload/Download:

    // Upload from string
    $client->upload('/remote/path/file.txt', 'file content');
    
    // Upload from file resource
    $client->upload('/remote/path/file.txt', fopen('local-file.txt', 'r'));
    
    // Download to string
    $content = $client->download('/remote/path/file.txt');
    
    // Download to file
    $client->download('/remote/path/file.txt', fopen('local-file.txt', 'w'));
    
  • Move/Rename:

    $client->move('/old/path/file.txt', '/new/path/file.txt', autorename: true);
    
  • Delete:

    $client->delete('/path/to/file.txt');
    

Folder Operations

  • Create Folder:

    $client->createFolder('/path/to/new-folder');
    
  • List Folder (with pagination):

    $contents = $client->listFolder('/path/to/folder');
    $nextBatch = $client->listFolderContinue($contents['cursor']);
    

Shared Links

  • Generate Temporary/Shared Links:

    $tempLink = $client->getTemporaryLink('/path/to/file.txt');
    $sharedLink = $client->createSharedLink('/path/to/file.txt');
    
  • List Shared Links:

    $links = $client->listSharedLinks('/path/to/folder');
    

Search

$results = $client->search('', 'query-term');

Integration with Laravel

Service Provider Setup

// config/services.php
'dropbox' => [
    'token' => env('DROPBOX_ACCESS_TOKEN'),
    'app_key' => env('DROPBOX_APP_KEY'),
    'app_secret' => env('DROPBOX_APP_SECRET'),
],

// app/Providers/AppServiceProvider.php
use Spatie\Dropbox\Client;

public function register()
{
    $this->app->singleton(Client::class, function ($app) {
        $token = config('services.dropbox.token');
        return new Client($token);
    });
}

Using Dependency Injection

use Spatie\Dropbox\Client;

public function __construct(Client $dropbox)
{
    $this->dropbox = $dropbox;
}

public function syncLocalToDropbox()
{
    $this->dropbox->upload('/remote/path/file.txt', file_get_contents('local-file.txt'));
}

Handling Token Refresh (OAuth2)

use Spatie\Dropbox\TokenProvider;
use League\OAuth2\Client\Provider\Dropbox as DropboxProvider;

class DropboxTokenProvider implements TokenProvider
{
    public function __construct(private DropboxProvider $provider, private string $refreshToken)
    {
    }

    public function getToken(): string
    {
        $token = $this->provider->getAccessToken('refresh_token', [
            'refresh_token' => $this->refreshToken,
        ]);
        return $token->getToken();
    }
}

// Usage
$tokenProvider = new DropboxTokenProvider($oauthProvider, $refreshToken);
$client = new Client($tokenProvider);

Advanced Patterns

Chunked Uploads (Large Files)

// Start a session
$sessionId = $client->uploadSessionStart();

// Upload chunks
$client->uploadSessionAppend($sessionId, fopen('large-file.txt', 'r'));

// Finish upload
$client->uploadSessionFinish($sessionId, '/remote/path/large-file.txt');

Custom Endpoints

// Direct RPC request
$response = $client->rpcEndpointRequest('files/get_metadata', [
    'path' => '/path/to/file.txt',
]);

// Content endpoint request
$response = $client->contentEndpointRequest('files/download', [], fopen('local-file.txt', 'w'));

Error Handling

try {
    $client->upload('/path/file.txt', 'content');
} catch (\Spatie\Dropbox\Exceptions\DropboxException $e) {
    // Handle specific errors (e.g., path conflict)
    if ($e->getErrorCode() === 'path/conflict') {
        $client->upload('/path/file.txt', 'content', autorename: true);
    }
}

Gotchas and Tips

Common Pitfalls

  1. Token Expiration:

    • Dropbox now uses short-lived access tokens. Always implement TokenProvider for OAuth2 flows to handle refreshes.
    • Example error: access_token_expired.
  2. Path Conflicts:

    • Use autorename: true in upload() or move() to avoid path/conflict errors.
    • Example:
      $client->upload('/path/file.txt', 'content', autorename: true);
      
  3. Large File Uploads:

    • For files > 150MB, use chunked uploads (uploadSessionStart, uploadSessionAppend, uploadSessionFinish).
    • Default chunk size is 4MB; adjust if needed via Guzzle middleware.
  4. Shared Link Settings:

    • Empty settings in createSharedLinkWithSettings may cause issues. Pass an empty array explicitly:
      $client->createSharedLinkWithSettings('/path/file.txt', []);
      
  5. Business Accounts:

    • Ensure your app is configured for Dropbox Business if targeting business accounts. Use the namespace_id parameter:
      $client->setNamespaceId('namespace-id');
      

Debugging Tips

  1. Enable Guzzle Debugging: Add middleware to log requests/responses:

    use GuzzleHttp\Middleware;
    
    $stack = \GuzzleHttp\HandlerStack::create();
    $stack->push(Middleware::tap(function ($request) {
        \Log::debug('Dropbox Request:', [
            'url' => (string) $request->getUri(),
            'method' => $request->getMethod(),
            'body' => (string) $request->getBody(),
        ]);
    }));
    
    $client = new Client($token, [], $stack);
    
  2. Inspect Raw Responses: Use rpcEndpointRequest or contentEndpointRequest to debug low-level API calls:

    $response = $client->rpcEndpointRequest('files/get_metadata', ['path' => '/file.txt']);
    \Log::debug('Raw Response:', $response);
    
  3. Handle Rate Limits: Dropbox may return 429 Too Many Requests. Retry with exponential backoff:

    use GuzzleHttp\Exception\RequestException;
    
    try {
        $client->upload('/file.txt', 'content');
    } catch (RequestException $e) {
        if ($e->getCode() === 429) {
            sleep(2); // Exponential backoff logic here
            retry();
        }
    }
    

Configuration Quirks

  1. Subdomain Handling: Prefix endpoints with subdomain:: for custom subdomains:

    $client->rpcEndpointRequest('content::files/get_thumbnail_batch', $params);
    
  2. Public Endpoints: Initialize the client without arguments for public access:

    $client = new Client(); // Uses public API endpoints
    
  3. App Authentication: Use [appKey, appSecret] for app-level authentication (no user token required):

    $client = new Client([$appKey, $appSecret]);
    

Extension Points

  1. Custom HTTP Client: Replace the default Guzzle client by binding a custom instance:

    $client = new Client($token, [], $customGuzzleClient);
    
  2. Add New Methods: Extend the Client class or use rpcEndpointRequest for unsupported endpoints:

    // Example: Add a custom method
    $client->rpcEndpointRequest('new/endpoint', ['param' => 'value']);
    
  3. Event Listeners: Listen for Dropbox API events (e.g., file uploads) using Laravel's event system:

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata