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

Api Client Laravel Package

2gis/api-client

PHP-клиент для API 2ГИС: регионы, справочник/каталог, транспорт и геоданные. Установка через Composer, простой вызов методов API 2.0 и работа с ответами сервиса. Лицензия MIT.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer (note: use dev-master as no stable release exists):
    composer require 2gis/api-client:dev-master
    
  2. Register the client in AppServiceProvider:
    public function register()
    {
        $this->app->singleton('2gis.client', function ($app) {
            return new \TwoGis\Client(config('services.2gis.key'));
        });
    }
    
  3. Add config to config/services.php:
    '2gis' => [
        'key' => env('TWOGIS_API_KEY'),
        'timeout' => 30,
    ],
    
  4. First API call (example: fetch regions):
    $regions = app('2gis.client')->regions()->getAll();
    

First Use Case: Local Business Search

// Search for businesses in a region (e.g., Moscow)
$search = app('2gis.client')->catalog()->search([
    'region' => 'moscow',
    'category' => 'restaurants',
    'limit' => 10,
]);

Implementation Patterns

Core Workflows

  1. Service Provider Pattern Bind the client to Laravel’s container for dependency injection:

    // app/Providers/2gisServiceProvider.php
    public function register()
    {
        $this->app->bind('2gis', function ($app) {
            return new \TwoGis\Client($app['config']['services.2gis.key']);
        });
    }
    
  2. Facade for Clean Access Create a facade to simplify usage:

    // app/Facades/2gis.php
    public static function regions()
    {
        return app('2gis')->regions();
    }
    

    Usage:

    $regions = \Facade\2gis::regions()->getAll();
    
  3. Repository Pattern Encapsulate API calls in repositories:

    // app/Repositories/2gis/RegionRepository.php
    public function findById($id)
    {
        return app('2gis')->regions()->getById($id);
    }
    
  4. Queue-Based API Calls Offload heavy requests to queues (e.g., bulk geodata fetches):

    // Dispatch a job
    dispatch(new FetchRegionsJob());
    
    // Job implementation
    public function handle()
    {
        $regions = app('2gis')->regions()->getAll();
        // Process regions...
    }
    

Integration Tips

  • Rate Limiting: Use Laravel’s throttle middleware or spatie/rate-limiter:
    Route::middleware(['throttle:100,1'])->group(function () {
        Route::get('/search', [SearchController::class, 'index']);
    });
    
  • Caching: Cache responses with Illuminate\Support\Facades\Cache:
    $regions = Cache::remember('2gis.regions', now()->addHours(1), function () {
        return app('2gis')->regions()->getAll();
    });
    
  • Error Handling: Wrap API calls in try-catch blocks:
    try {
        $data = app('2gis')->catalog()->search($params);
    } catch (\TwoGis\Exception\ApiException $e) {
        Log::error("2GIS API Error: " . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    

Laravel-Specific Extensions

  1. Eloquent Models Attach geodata to models:

    // app/Models/Business.php
    public function getCoordinatesAttribute()
    {
        $geo = app('2gis')->geo()->getById($this->geo_id);
        return [$geo['lon'], $geo['lat']];
    }
    
  2. Scout Driver Create a custom Scout driver for 2GIS geospatial search:

    // app/Search/2gisEngine.php
    public function search($query)
    {
        return app('2gis')->catalog()->search([
            'q' => $query,
            'limit' => 100,
        ]);
    }
    
  3. API Resources Format responses with Laravel’s API Resources:

    // app/Http/Resources/RegionResource.php
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'full_name' => $this->full_name,
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated PHP Features

    • The package may use curl_init(), json_decode() without associative flag, or other deprecated functions.
    • Fix: Use rector to upgrade:
      composer require rector/rector --dev
      vendor/bin/rector process src --dry-run
      
  2. No Type Safety

    • API responses are untyped arrays. Validate with Illuminate\Support\Facades\Validator:
      $validator = Validator::make($response, [
          'id' => 'required|integer',
          'name' => 'required|string',
      ]);
      
  3. Hardcoded Endpoints

    • The package may hardcode API URLs (e.g., api.2gis.com). Override via config:
      // config/2gis.php
      'endpoints' => [
          'regions' => env('TWOGIS_REGIONS_ENDPOINT', 'https://api.2gis.com/2.0/regions'),
      ],
      
  4. No Retry Logic

    • Transient failures (e.g., network issues) aren’t retried. Implement with Guzzle middleware:
      $client = new \TwoGis\Client($apiKey, [
          'http_client' => Http::withOptions([
              'timeout' => 30,
              'connect_timeout' => 10,
              'retry' => true,
          ]),
      ]);
      
  5. Alpha-Stage APIs

    • Transport and geodata APIs are marked as unstable. Test thoroughly and expect changes.

Debugging Tips

  1. Enable API Logging Add a logger to the client:

    $client = new \TwoGis\Client($apiKey, [
        'logger' => function () {
            return new \Monolog\Logger('2gis');
        },
    ]);
    
  2. Inspect Raw Responses Use dd() or Log::debug() to inspect raw API responses:

    $response = app('2gis')->regions()->getAll();
    Log::debug('Raw 2GIS response:', $response);
    
  3. Mock the Client for Testing Use Laravel’s mocking to test without hitting the API:

    $this->mock(\TwoGis\Client::class)->shouldReceive('regions')
        ->andReturnSelf()
        ->shouldReceive('getAll')
        ->andReturn([/* mock data */]);
    

Extension Points

  1. Custom HTTP Client Replace the default HTTP client (likely curl) with Guzzle:

    $client = new \TwoGis\Client($apiKey, [
        'http_client' => new \GuzzleHttp\Client(),
    ]);
    
  2. Add New API Endpoints Extend the client class to support unsupported APIs:

    // app/Extensions/2gis/ClientExtension.php
    public function customEndpoint($params)
    {
        return $this->request('GET', '/custom', $params);
    }
    
  3. Webhook Support If 2GIS offers webhooks, create a Laravel event listener:

    // app/Listeners/Handle2gisWebhook.php
    public function handle($event)
    {
        $data = $event->data;
        // Process webhook data...
    }
    

Configuration Quirks

  1. API Key Format Ensure your API key matches the expected format (e.g., Bearer token vs. plain key). Check 2GIS docs.

  2. Region Codes 2GIS uses internal region codes (e.g., moscow vs. 1). Validate against their region list.

  3. Pagination The package may not handle pagination. Implement manually:

    $offset = 0;
    $limit = 100;
    do {
        $results = app('2gis')->catalog()->search([
            'offset' => $offset,
            'limit' => $limit,
        ]);
        // Process $results
        $offset += $limit;
    } while (!empty($results));
    

Performance Tips

  1. Batch Requests Use 2GIS’s batch endpoints (if available) to reduce API calls:
    $ids = [1,
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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