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

Simple Api Client Bundle Laravel Package

alxxc/simple-api-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alxxc/simple-api-client-bundle:dev-master
    

    Add to config/bundles.php:

    return [
        // ...
        SimpleApiClientBundle\SimpleApiClientBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Inject the service into a controller or service:

    use SimpleApiClientBundle\Client\SimpleApiClientInterface;
    
    class LocationController extends AbstractController
    {
        public function __construct(private SimpleApiClientInterface $apiClient) {}
    
        public function getLocations()
        {
            $url = 'https://api.example.com/locations';
            $locations = $this->apiClient->loadLocations($url);
            return $this->json($locations);
        }
    }
    
  3. Key Files:

    • config/packages/simple_api_client.yaml (if auto-generated)
    • src/SimpleApiClientBundle/ (core logic)

Implementation Patterns

Core Workflows

  1. API Integration:

    • Use loadLocations($url) to fetch and parse JSON data from a predefined API endpoint.
    • Example: Fetching geolocation data for a frontend map:
      $locations = $this->apiClient->loadLocations('https://api.example.com/geodata');
      return $this->render('map.html.twig', ['locations' => $locations]);
      
  2. Dependency Injection:

    • Prefer constructor injection for testability:
      public function __construct(SimpleApiClientInterface $client) {}
      
  3. Caching Responses (if extended):

    • Override the service to cache responses (e.g., using Symfony Cache component):
      # config/services.yaml
      services:
          App\Service\CachedApiClient:
              decorates: 'simple_api_client.client'
              arguments: ['@.inner']
      
  4. Error Handling:

    • Wrap API calls in try-catch blocks:
      try {
          $data = $this->apiClient->loadLocations($url);
      } catch (\RuntimeException $e) {
          $this->addFlash('error', 'Failed to fetch data: ' . $e->getMessage());
      }
      
  5. Configuration:

    • Customize default behavior via config/packages/simple_api_client.yaml:
      simple_api_client:
          default_timeout: 30
          user_agent: 'MyApp/1.0'
      

Gotchas and Tips

Pitfalls

  1. No Built-in Rate Limiting:

    • The bundle uses Guzzle under the hood but lacks rate-limiting logic. Add middleware if needed:
      $client = new \GuzzleHttp\Client([
          'timeout' => 10,
          'headers' => ['User-Agent' => 'MyApp/1.0'],
      ]);
      
  2. Assumes JSON Structure:

    • The loadLocations() method expects a specific JSON format. Validate responses:
      $data = $this->apiClient->loadLocations($url);
      if (!isset($data['locations'])) {
          throw new \RuntimeException('Invalid API response format');
      }
      
  3. Symfony 3.4 Only:

    • The package targets Symfony 3.4. For newer versions, check compatibility or fork the package.
  4. No Retry Logic:

    • Transient failures (e.g., network issues) won’t auto-retry. Implement retry logic manually:
      use GuzzleHttp\Exception\RequestException;
      
      try {
          $this->apiClient->loadLocations($url);
      } catch (RequestException $e) {
          if ($e->hasResponse() && $e->getResponse()->getStatusCode() === 503) {
              sleep(2); // Retry after delay
              return $this->getLocations(); // Recursive call
          }
      }
      

Tips

  1. Extend the Client:

    • Create a custom client class to add features:
      namespace App\Service;
      
      use SimpleApiClientBundle\Client\SimpleApiClientInterface;
      
      class EnhancedApiClient implements SimpleApiClientInterface
      {
          public function __construct(private SimpleApiClientInterface $decorated) {}
      
          public function loadLocations(string $url): array
          {
              $data = $this->decorated->loadLocations($url);
              return $this->transformData($data); // Add custom logic
          }
      }
      
  2. Logging:

    • Log API calls for debugging:
      # config/services.yaml
      services:
          simple_api_client.client:
              calls:
                  - [setLogger, ['@logger']]
      
  3. Testing:

    • Mock the client in tests:
      $mockClient = $this->createMock(SimpleApiClientInterface::class);
      $mockClient->method('loadLocations')->willReturn(['test' => 'data']);
      $this->container->set('simple_api_client.client', $mockClient);
      
  4. Configuration Overrides:

    • Override Guzzle defaults via DI:
      services:
          simple_api_client.client:
              arguments:
                  $client: '@custom.guzzle.client'
      
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
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