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-check/php-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require api-check/php-client
    

    Ensure your project meets PHP 8.1+ requirements.

  2. First Use Case: API Health Check

    use ApiCheck\Client;
    
    $client = new Client('https://api.example.com');
    $response = $client->check();
    
    if ($response->isHealthy()) {
        echo "API is healthy!";
    } else {
        echo "API issues detected: " . $response->getErrors();
    }
    
  3. Key Files to Explore

    • src/Client.php – Core client logic.
    • src/Response.php – Response handling and validation.
    • tests/ – Example use cases and edge cases.

Implementation Patterns

Workflow: Integrating with Laravel

  1. Service Provider Binding

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Client::class, function ($app) {
            return new Client(config('services.api_check.endpoint'));
        });
    }
    
  2. Configuration

    // config/services.php
    'api_check' => [
        'endpoint' => env('API_CHECK_ENDPOINT', 'https://api.example.com'),
        'timeout' => 5.0,
        'headers' => [
            'Authorization' => 'Bearer ' . env('API_CHECK_TOKEN'),
        ],
    ],
    
  3. Middleware for API Guarding

    // app/Http/Middleware/CheckApiHealth.php
    public function handle($request, Closure $next)
    {
        $client = app(Client::class);
        $response = $client->check();
    
        if (!$response->isHealthy()) {
            return response()->json(['error' => 'API Unavailable'], 503);
        }
    
        return $next($request);
    }
    
  4. Scheduled Monitoring

    // app/Console/Commands/MonitorApi.php
    use Illuminate\Console\Command;
    use ApiCheck\Client;
    
    class MonitorApi extends Command
    {
        protected $signature = 'api:monitor';
        public function handle()
        {
            $client = new Client(config('services.api_check.endpoint'));
            $response = $client->check();
    
            if (!$response->isHealthy()) {
                $this->error("API Unhealthy: " . $response->getErrors());
                // Send alert (e.g., Slack, Email)
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Timeout Handling

    • Default timeout may be too short for slow APIs. Configure via:
      $client = new Client('https://api.example.com', ['timeout' => 10.0]);
      
    • Tip: Log timeout errors for debugging:
      try {
          $response = $client->check();
      } catch (ConnectException $e) {
          Log::error("API Connection Failed: " . $e->getMessage());
      }
      
  2. Response Parsing Quirks

    • The package assumes a standard JSON response with healthy and errors fields.
    • Fix: Extend Response class to handle custom formats:
      class CustomResponse extends Response
      {
          public function isHealthy(): bool
          {
              return $this->data['status'] === 'ok';
          }
      }
      
  3. Rate Limiting

    • Aggressive polling may hit API rate limits. Use exponential backoff:
      use Symfony\Component\Process\Exception\TimeoutException;
      
      try {
          $response = $client->check();
      } catch (TimeoutException $e) {
          sleep(2); // Retry after delay
          retry();
      }
      
  4. HTTPS/SSL Issues

    • Self-signed certificates may cause failures. Disable verification (temporarily for testing):
      $client = new Client('https://api.example.com', [
          'verify_peer' => false,
      ]);
      
    • Tip: Use Laravel’s trusted_proxies or config/cors.php for proxy setups.

Extension Points

  1. Custom Endpoints Override the default /health endpoint:

    $client = new Client('https://api.example.com', ['endpoint' => '/custom-health']);
    
  2. Adding Metrics Integrate with Laravel Telescope or Prometheus:

    $response = $client->check();
    \Prometheus\CollectorRegistry::default()->getOrRegisterCounter(
        'api_health_checks_total',
        'Total API health checks',
        ['status' => $response->isHealthy() ? 'healthy' : 'unhealthy']
    )->inc();
    
  3. Mocking for Tests Use Laravel’s HTTP mocking:

    use Illuminate\Support\Facades\Http;
    
    Http::fake([
        'https://api.example.com/health' => Http::response(['healthy' => true]),
    ]);
    
    $this->assertTrue($client->check()->isHealthy());
    
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.
cadot.eu/make
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