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

Bitbucket Api Laravel Package

gentle/bitbucket-api

PHP Bitbucket API wrapper (PHP 5.4+) using cURL and Buzz. Provides a simple client for interacting with Bitbucket endpoints, with full documentation and optional PHPUnit test suite. MIT licensed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require gentle/bitbucket-api
    

    Requires PHP ≥ 5.4 with cURL and Buzz library.

  2. First Use Case: Authenticate and fetch a repository:

    use Gentle\Bitbucket\Client;
    
    $client = new Client('your_app_name', 'your_consumer_key', 'your_private_key');
    $client->setAuth('username', 'password'); // or OAuth token
    
    $repo = $client->repositories()->get('account_name', 'repo_slug');
    
  3. Where to Look First:

    • Official Documentation
    • /docs/examples/ for API-specific examples (e.g., repositories/repository.md for CRUD operations).

Implementation Patterns

Authentication Workflow

  1. OAuth2 or Basic Auth:

    // OAuth2 (recommended for production)
    $client = new Client('app_name', 'consumer_key', 'private_key');
    $client->setAuth('username', 'password'); // or OAuth token
    
    // Or via token
    $client->setAuthToken('oauth_token');
    
  2. Service Container Integration (Laravel): Bind the client in AppServiceProvider:

    $this->app->singleton('bitbucket', function ($app) {
        $client = new Client(config('bitbucket.app_name'), config('bitbucket.consumer_key'), config('bitbucket.private_key'));
        $client->setAuthToken(config('bitbucket.oauth_token'));
        return $client;
    });
    

Common CRUD Patterns

  1. Repository Operations:

    // Create
    $repo = $client->repositories()->create('account', 'repo-slug', [
        'scm' => 'git',
        'is_private' => true,
    ]);
    
    // Update
    $client->repositories()->update('account', 'repo-slug', ['description' => 'Updated']);
    
    // Fetch issues
    $issues = $client->repositories()->issues()->all('account', 'repo-slug', ['limit' => 10]);
    
  2. Pagination Handling: Use limit/start for paginated endpoints (e.g., issues, commits):

    $issues = $client->repositories()->issues()->all('account', 'repo-slug', [
        'limit' => 20,
        'start' => 0,
    ]);
    
  3. Error Handling: Wrap API calls in try-catch:

    try {
        $repo = $client->repositories()->get('account', 'repo-slug');
    } catch (\Gentle\Bitbucket\Exception\BitbucketException $e) {
        Log::error('Bitbucket API Error: ' . $e->getMessage());
        return response()->json(['error' => 'Failed to fetch repo'], 500);
    }
    

Integration Tips

  1. Laravel Artisan Commands: Use the client in scheduled tasks (e.g., syncing Bitbucket issues to a local DB):

    use Gentle\Bitbucket\Client;
    
    class SyncIssuesCommand extends Command {
        protected $client;
    
        public function __construct(Client $client) {
            parent::__construct();
            $this->client = $client;
        }
    
        public function handle() {
            $issues = $this->client->repositories()->issues()->all('account', 'repo-slug');
            // Process issues...
        }
    }
    
  2. Event Listeners: Trigger actions on Bitbucket webhooks (e.g., repository:updated):

    public function handle(RepositoryUpdated $event) {
        $repo = $this->client->repositories()->get($event->account, $event->repo);
        // Update local cache or notify team.
    }
    
  3. Caching Responses: Cache frequent API calls (e.g., repository metadata) using Laravel’s cache:

    $repo = Cache::remember("bitbucket_repo_{$account}_{$slug}", now()->addHours(1), function () use ($client, $account, $slug) {
        return $client->repositories()->get($account, $slug);
    });
    

Gotchas and Tips

Pitfalls

  1. API Version Mismatches:

    • The package supports API 1.0 (deprecated) and API 2.0. Ensure you use the correct endpoint (e.g., repo->create() for API 2.0).
    • Example: Repository creation in API 1.0 omits account_name and scm fields.
  2. Authentication Timeouts:

    • OAuth tokens expire. Implement token refresh logic or use short-lived tokens with a refresh flow.
    • Workaround: Store tokens in the database and validate their expiry before use.
  3. Rate Limiting:

    • Bitbucket enforces rate limits. Handle 429 Too Many Requests gracefully:
      if ($e->getCode() === 429) {
          sleep($e->getRetryAfter()); // Respect Retry-After header
          retry();
      }
      
  4. Missing Endpoints:

    • Some endpoints (e.g., changesets->likes()) are not implemented due to API bugs. Check the issue tracker for updates.
  5. Case Sensitivity:

    • Repository slugs and branch names are case-sensitive in Bitbucket. Validate inputs:
      $repoSlug = strtolower($request->input('repo_slug'));
      

Debugging Tips

  1. Enable Verbose Logging: Configure Buzz to log requests/responses:

    $client->getBuzzClient()->setLogger(new \Gentle\Bitbucket\Logger\FileLogger('/path/to/bitbucket.log'));
    
  2. Inspect Raw Responses: Use getLastResponse() to debug failed requests:

    try {
        $repo = $client->repositories()->get('account', 'repo-slug');
    } catch (\Exception $e) {
        $response = $client->getLastResponse();
        Log::error("Response: " . $response->getContent());
    }
    
  3. Common HTTP Errors:

    • 401 Unauthorized: Invalid credentials or expired token.
    • 403 Forbidden: Lack of permissions (e.g., accessing a private repo).
    • 404 Not Found: Invalid account_name/repo_slug or branch/tag.

Extension Points

  1. Custom Requests: Use the underlying Buzz client for unsupported endpoints:

    $response = $client->getBuzzClient()->get("https://api.bitbucket.org/2.0/repositories/{$account}/{$repo}/pullrequests");
    
  2. Middleware for Requests: Add headers or modify requests globally:

    $client->getBuzzClient()->getEventDispatcher()->addListener('request.before_send', function ($request) {
        $request->setHeader('X-Api-Key', config('bitbucket.api_key'));
    });
    
  3. Mocking for Tests: Use Laravel’s HTTP mocking or replace the client with a mock in tests:

    $this->partialMock(Client::class, ['repositories'])
         ->shouldReceive('get')
         ->andReturn(new Repository(['name' => 'test-repo']));
    

Configuration Quirks

  1. Private Key Format: Ensure the private key is in PEM format and properly formatted for OAuth:

    -----BEGIN RSA PRIVATE KEY-----
    (your private key here)
    -----END RSA PRIVATE KEY-----
    
  2. SSL Verification: Disable SSL verification only for testing (not production):

    $client->getBuzzClient()->setDefaultOption('verify_peer', false);
    
  3. Proxy Support: Configure Buzz to use a proxy:

    $client->getBuzzClient()->setDefaultOption('proxy', 'http://proxy.example.com:8080');
    
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata