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.
Installation:
composer require gentle/bitbucket-api
Requires PHP ≥ 5.4 with cURL and Buzz library.
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');
Where to Look First:
/docs/examples/ for API-specific examples (e.g., repositories/repository.md for CRUD operations).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');
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;
});
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]);
Pagination Handling:
Use limit/start for paginated endpoints (e.g., issues, commits):
$issues = $client->repositories()->issues()->all('account', 'repo-slug', [
'limit' => 20,
'start' => 0,
]);
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);
}
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...
}
}
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.
}
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);
});
API Version Mismatches:
repo->create() for API 2.0).account_name and scm fields.Authentication Timeouts:
Rate Limiting:
429 Too Many Requests gracefully:
if ($e->getCode() === 429) {
sleep($e->getRetryAfter()); // Respect Retry-After header
retry();
}
Missing Endpoints:
changesets->likes()) are not implemented due to API bugs. Check the issue tracker for updates.Case Sensitivity:
$repoSlug = strtolower($request->input('repo_slug'));
Enable Verbose Logging: Configure Buzz to log requests/responses:
$client->getBuzzClient()->setLogger(new \Gentle\Bitbucket\Logger\FileLogger('/path/to/bitbucket.log'));
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());
}
Common HTTP Errors:
account_name/repo_slug or branch/tag.Custom Requests: Use the underlying Buzz client for unsupported endpoints:
$response = $client->getBuzzClient()->get("https://api.bitbucket.org/2.0/repositories/{$account}/{$repo}/pullrequests");
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'));
});
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']));
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-----
SSL Verification: Disable SSL verification only for testing (not production):
$client->getBuzzClient()->setDefaultOption('verify_peer', false);
Proxy Support: Configure Buzz to use a proxy:
$client->getBuzzClient()->setDefaultOption('proxy', 'http://proxy.example.com:8080');
How can I help you explore Laravel packages today?