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

Polr Api Client Laravel Package

adeelnawaz/polr-api-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require adeelnawaz/polr-api-client
    

    Ensure composer.json includes "minimum-stability": "dev" if the package is in development.

  2. 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();
    
  3. Where to Look First

    • Documentation: Check the Polr API docs for endpoint references.
    • Client Class: Browse src/Client.php for core methods (get, post, put, delete).
    • Exceptions: Review src/Exceptions/ for error handling (e.g., ApiException).

Implementation Patterns

Usage Patterns

  1. 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();
    
  2. 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']);
    
  3. Webhook Integration Validate incoming Polr webhook payloads:

    $payload = json_decode(file_get_contents('php://input'), true);
    $client->validateWebhook($payload, config('polr.webhook_secret'));
    

Workflows

  1. Link Shortening Service

    • Use post('/api/v1/links') to create short URLs.
    • Store the returned short_code in your database for tracking.
    • Redirect users via redirect("https://polr.me/{$short_code}").
  2. Analytics Dashboard Fetch link analytics with:

    $analytics = $client->get("/api/v1/links/{$linkId}/analytics")->json();
    

    Plot data using Laravel Charts or similar.

  3. 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']]
        );
    }
    

Integration Tips

  • 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);
    

Gotchas and Tips

Pitfalls

  1. Authentication Failures

    • Symptom: 401 Unauthorized or empty responses.
    • Fix: Verify api_key in .env and ensure it has the correct permissions in Polr.
    • Debug: Check the Authorization header in the raw request (use dd($client->getLastRequest())).
  2. Endpoint Changes

    • Polr’s API may evolve. Test endpoints against the latest docs.
    • Workaround: Use feature flags or config overrides for deprecated endpoints.
  3. Webhook Verification

    • Gotcha: Webhook payloads must match the X-Signature header.
    • Fix: Always validate with $client->validateWebhook($payload, $secret).
  4. Pagination Quirks

    • Some endpoints use ?page=1 while others use ?offset=0. Check the response meta for pagination details.

Debugging

  • 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

Config Quirks

  • 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']);
    

Extension Points

  1. 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)
            ]);
        }
    }
    
  2. Event Listeners Trigger Laravel events on Polr webhooks:

    Event::listen('polr.webhook.received', function ($payload) {
        // Dispatch custom event
        event(new LinkClicked($payload['link_id']));
    });
    
  3. Middleware Add middleware to the client for logging or auth:

    $client->withMiddleware(function ($request) {
        $request->headers->set('X-Request-ID', Str::uuid());
    });
    
  4. Model Observers Sync Polr data with Eloquent models:

    class PolrLinkObserver {
        public function saved(PolrLink $link) {
            $client->post('/api/v1/links', $link->toArray());
        }
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope