Installation
composer require adeelnawaz/polr-api-client
Ensure composer.json includes "minimum-stability": "dev" if the package is in development.
First Use Case: Authentication Initialize the client with your Polr API credentials:
use AdeelNawaz\PolrApiClient\Client;
$client = new Client(
config('polr.api_url'),
config('polr.api_key')
);
Verify credentials by fetching a simple endpoint (e.g., /api/v1/links):
$links = $client->get('/api/v1/links')->json();
Where to Look First
src/Client.php for core methods (get, post, put, delete).src/Exceptions/ for error handling (e.g., ApiException).Resource Management Use the client to CRUD Polr resources (links, users, settings):
// Create a link
$response = $client->post('/api/v1/links', [
'title' => 'My Link',
'url' => 'https://example.com',
'description' => 'Test link'
]);
// Fetch a specific link
$link = $client->get("/api/v1/links/{$response->id}")->json();
Pagination Handling
Loop through paginated results (e.g., /api/v1/links?page=1):
$page = 1;
do {
$links = $client->get("/api/v1/links?page={$page}")->json();
foreach ($links['data'] as $link) {
// Process link
}
$page = $links['meta']['current_page'] + 1;
} while ($page <= $links['meta']['last_page']);
Webhook Integration Validate incoming Polr webhook payloads:
$payload = json_decode(file_get_contents('php://input'), true);
$client->validateWebhook($payload, config('polr.webhook_secret'));
Link Shortening Service
post('/api/v1/links') to create short URLs.short_code in your database for tracking.redirect("https://polr.me/{$short_code}").Analytics Dashboard Fetch link analytics with:
$analytics = $client->get("/api/v1/links/{$linkId}/analytics")->json();
Plot data using Laravel Charts or similar.
User Management Sync Polr users with your Laravel users table:
$users = $client->get('/api/v1/users')->json();
foreach ($users as $user) {
User::updateOrCreate(
['email' => $user['email']],
['polr_id' => $user['id']]
);
}
Laravel Service Provider
Bind the client in AppServiceProvider for dependency injection:
$this->app->singleton(Client::class, function ($app) {
return new Client(
config('polr.api_url'),
config('polr.api_key')
);
});
Use in controllers:
public function __construct(private Client $polr) {}
API Rate Limiting Implement exponential backoff for rate-limited requests:
use AdeelNawaz\PolrApiClient\Exceptions\RateLimitExceededException;
try {
$response = $client->get('/api/v1/links');
} catch (RateLimitExceededException $e) {
sleep($e->retryAfter);
retry();
}
Testing Mock the client in PHPUnit:
$mock = Mockery::mock(Client::class);
$mock->shouldReceive('get')->once()->andReturn((object) ['id' => 1]);
$this->app->instance(Client::class, $mock);
Authentication Failures
401 Unauthorized or empty responses.api_key in .env and ensure it has the correct permissions in Polr.Authorization header in the raw request (use dd($client->getLastRequest())).Endpoint Changes
Webhook Verification
X-Signature header.$client->validateWebhook($payload, $secret).Pagination Quirks
?page=1 while others use ?offset=0. Check the response meta for pagination details.Enable Debug Mode
Set config(['polr.debug' => true]) to log raw requests/responses to storage/logs/polr.log.
Inspect Headers Dump the last request/response:
dd($client->getLastRequest(), $client->getLastResponse());
Common HTTP Errors
| Error Code | Cause | Solution |
|---|---|---|
| 404 | Endpoint not found | Verify URL and API version |
| 429 | Rate limit exceeded | Implement retry logic |
| 500 | Server error | Check Polr server status |
API URL
Ensure config('polr.api_url') ends with / (e.g., https://polr.me/api/v1/).
Relative paths (e.g., /api/v1/links) will be appended.
Default Headers
The client auto-adds Accept: application/json and Authorization. Override with:
$client->withHeaders(['X-Custom-Header' => 'value']);
Custom Requests Extend the client for non-REST actions:
class CustomPolrClient extends Client {
public function uploadLogo($filePath) {
return $this->post('/api/v1/settings/logo', [
'logo' => new \Cviebrock\EloquentSluggable\Services\FileUpload($filePath)
]);
}
}
Event Listeners Trigger Laravel events on Polr webhooks:
Event::listen('polr.webhook.received', function ($payload) {
// Dispatch custom event
event(new LinkClicked($payload['link_id']));
});
Middleware Add middleware to the client for logging or auth:
$client->withMiddleware(function ($request) {
$request->headers->set('X-Request-ID', Str::uuid());
});
Model Observers Sync Polr data with Eloquent models:
class PolrLinkObserver {
public function saved(PolrLink $link) {
$client->post('/api/v1/links', $link->toArray());
}
}
How can I help you explore Laravel packages today?