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

Php Client Laravel Package

api-postcode/php-client

PHP client for api-postcode.nl to look up Dutch address details by postcode and house number. Install via Composer, create a PostcodeClient with your token, and fetch street, city, house number, zip code, latitude, and longitude.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require api-postcode/php-client
    

    Add to composer.json if using a custom package name (e.g., api-postcode/php-postcode).

  2. First Request

    use ApiPostcode\Client;
    
    $client = new Client('YOUR_API_KEY');
    $response = $client->getPostcode('EC1A 1BB'); // Example UK postcode
    dd($response->getData());
    
  3. Key Files

    • src/Client.php: Core class for API interactions.
    • src/Response.php: Handles API responses (status, data, errors).
    • src/Exceptions/: Custom exceptions (e.g., ApiException).

First Use Case: Reverse Geocoding

$client = new Client('YOUR_API_KEY');
$response = $client->reverseGeocode(51.5074, -0.1278); // Latitude, Longitude
$address = $response->getData()['address'];

Implementation Patterns

Workflows

  1. Basic Requests

    • Use fluent methods for common endpoints:
      $client->getPostcode('SW1A 1AA');
      $client->reverseGeocode(51.5074, -0.1278);
      $client->autocomplete('London');
      
  2. Custom Endpoints Extend the Client class or use the low-level request() method:

    $response = $client->request('postcodes', ['postcode' => 'W1A 0AX']);
    
  3. Batch Processing Loop through postcodes with error handling:

    $postcodes = ['EC1A 1BB', 'SW1A 1AA', 'W1A 0AX'];
    foreach ($postcodes as $postcode) {
        try {
            $data = $client->getPostcode($postcode)->getData();
            // Process $data
        } catch (\ApiPostcode\Exceptions\ApiException $e) {
            Log::error("Failed for $postcode: " . $e->getMessage());
        }
    }
    

Integration Tips

  • Laravel Service Provider Bind the client to the container for dependency injection:

    $this->app->singleton(Client::class, function ($app) {
        return new Client(config('services.postcode.api_key'));
    });
    

    Usage in controllers:

    use ApiPostcode\Client;
    
    public function __construct(Client $client) {
        $this->client = $client;
    }
    
  • Caching Responses Cache responses for 1 hour (adjust TTL as needed):

    $cacheKey = "postcode_{$postcode}";
    $data = Cache::remember($cacheKey, now()->addHours(1), function () use ($client, $postcode) {
        return $client->getPostcode($postcode)->getData();
    });
    
  • Rate Limiting Implement a queue job for bulk requests to avoid hitting rate limits:

    PostcodeJob::dispatch($postcode)->onQueue('postcode');
    

Gotchas and Tips

Pitfalls

  1. API Key Management

    • Hardcoding keys in code violates security best practices. Use Laravel’s .env:
      POSTCODE_API_KEY=your_key_here
      
    • Never commit .env to version control.
  2. Error Handling

    • The package throws \ApiPostcode\Exceptions\ApiException for HTTP errors (e.g., 404, 429). Always wrap requests in try-catch:
      try {
          $client->getPostcode('INVALID_POSTCODE');
      } catch (\ApiPostcode\Exceptions\ApiException $e) {
          // Handle invalid postcode or rate limits
      }
      
  3. Deprecated Methods

    • The package is last updated in 2021. Check the API docs for breaking changes (e.g., endpoint URLs, response formats).
  4. Curl Configuration

    • The client uses curl under the hood. If you encounter SSL issues, configure defaults:
      $client = new Client('YOUR_API_KEY', [
          CURLOPT_SSL_VERIFYPEER => false, // Disable for testing (not recommended for production)
      ]);
      

Debugging

  • Enable Verbose Logging Pass a LoggerInterface to the client for debugging:

    use Psr\Log\LoggerInterface;
    
    $client = new Client('YOUR_API_KEY', [], new Monolog\Logger('postcode'));
    
  • Inspect Raw Responses Access the raw response object for debugging:

    $response = $client->getPostcode('EC1A 1BB');
    dd($response->getRawResponse()); // Full HTTP response
    

Extension Points

  1. Custom Response Parsing Extend the Response class to add custom parsing logic:

    class CustomResponse extends \ApiPostcode\Response {
        public function getFormattedAddress() {
            $data = $this->getData();
            return $data['address']['line1'] . ', ' . $data['address']['city'];
        }
    }
    
  2. Mocking for Tests Use Laravel’s HTTP client or mock the Client class:

    $mockClient = Mockery::mock(Client::class);
    $mockClient->shouldReceive('getPostcode')
               ->once()
               ->andReturn(new \ApiPostcode\Response(200, ['data' => ['postcode' => 'EC1A 1BB']]));
    
  3. Adding Headers Pass custom headers via the constructor:

    $client = new Client('YOUR_API_KEY', [
        'headers' => [
            'X-Custom-Header' => 'value',
        ],
    ]);
    

Configuration Quirks

  • Default Endpoint The client assumes the API endpoint is https://api.postcodes.io. Override it if using a custom URL:

    $client = new Client('YOUR_API_KEY', ['base_uri' => 'https://custom-api.example.com']);
    
  • Response Format The API returns JSON by default. If the response format changes, update the parseResponse() method in Client.php.

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor