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 Restclient Laravel Package

tcdent/php-restclient

Simple PHP REST client for making HTTP requests to JSON/REST APIs. Provides a clean interface for GET/POST/PUT/DELETE, headers and query params, basic authentication, and response handling to quickly integrate remote services without heavy dependencies.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require tcdent/php-restclient
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        TcDent\RestClient\RestClientServiceProvider::class,
    ],
    
  2. Basic Usage Inject the client via Laravel's dependency injection:

    use TcDent\RestClient\RestClient;
    
    class MyService {
        public function __construct(protected RestClient $client) {}
    
        public function fetchData() {
            $response = $this->client->get('https://api.example.com/data');
            return $response->getBody();
        }
    }
    
  3. First Use Case: API Wrapper Create a dedicated client instance for an API:

    $client = app(RestClient::class)
        ->setBaseUrl('https://api.example.com/v1')
        ->setDefaultHeaders(['Authorization' => 'Bearer token']);
    

Implementation Patterns

Core Workflows

  1. Request Customization

    // Per-request overrides
    $response = $client->get('/users', [
        'headers' => ['X-Custom-Header' => 'value'],
        'query'   => ['active' => true],
    ]);
    
  2. Response Handling

    $response = $client->post('/users', ['name' => 'John'], [
        'headers' => ['Content-Type' => 'application/json'],
    ]);
    
    // Parse JSON automatically
    $data = $response->getBodyAsJson();
    
    // Or access raw response
    $status = $response->getStatus();
    $headers = $response->getHeaders();
    
  3. Authentication

    // Basic Auth
    $client->setDefaultAuth('username', 'password');
    
    // Bearer Token
    $client->setDefaultHeaders(['Authorization' => 'Bearer ' . $token]);
    

Integration Tips

  • Middleware: Extend the client with middleware for logging, retries, or auth:

    $client->addMiddleware(function ($request) {
        $request->setHeader('X-Request-ID', uniqid());
    });
    
  • Rate Limiting: Use middleware to enforce rate limits:

    $client->addMiddleware(new RateLimitMiddleware(10, 60));
    
  • API Versioning: Create named clients for different API versions:

    $v1Client = app(RestClient::class)->setBaseUrl('https://api.example.com/v1');
    $v2Client = app(RestClient::class)->setBaseUrl('https://api.example.com/v2');
    
  • Testing: Mock responses in tests:

    $client->setMockResponse(new MockResponse(200, [], '{"test": true}'));
    

Gotchas and Tips

Common Pitfalls

  1. Header/Query Merging

    • Pre-encoded strings (e.g., ?query=encoded%20string) bypass merging. Use setQuery() or setHeaders() for dynamic values:
      // ❌ Bypasses merging
      $client->get('?query=' . urlencode('test'));
      
      // ✅ Proper merging
      $client->get('/', ['query' => ['test' => 'value']]);
      
  2. Response Parsing

    • Non-JSON responses (e.g., XML) require manual parsing:
      $xml = simplexml_load_string($response->getBody());
      
  3. SSL Verification

    • Disable SSL verification only in development (never in production):
      $client->setOptions(['verify' => false]); // ⚠️ Avoid in prod
      
  4. Idempotency

    • PATCH requests with JSON bodies require explicit content-type headers:
      $client->patch('/resource', ['key' => 'value'], [
          'headers' => ['Content-Type' => 'application/json'],
      ]);
      

Debugging Tips

  • Enable Verbose Logging

    $client->setOptions(['debug' => true]);
    

    Check Laravel logs for raw request/response details.

  • Inspect Headers Use dd($response->getHeaders()) to debug header issues.

  • Timeouts Set timeouts explicitly to avoid hanging:

    $client->setOptions(['timeout' => 30.0]);
    

Extension Points

  1. Custom Response Classes Extend TcDent\RestClient\Response to add domain-specific methods:

    class ApiResponse extends Response {
        public function getUser() {
            return $this->getBodyAsJson()['user'];
        }
    }
    
  2. Request Factories Create reusable request builders:

    $factory = new RequestFactory($client);
    $request = $factory->get('/users')->withQuery(['active' => true]);
    
  3. Event Listeners Attach listeners for pre/post-request logic:

    $client->addListener('before_request', function ($request) {
        $request->setHeader('X-Timestamp', now()->toIso8601String());
    });
    
  4. Retry Logic Implement exponential backoff middleware:

    $client->addMiddleware(new RetryMiddleware(3, function ($response) {
        return $response->getStatus() >= 500;
    }));
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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