Weave 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

Kiota Http Guzzle Laravel Package

microsoft/kiota-http-guzzle

The Kiota HTTP library for PHP provides a Guzzle-based HTTP transport for Kiota-generated API clients. Install microsoft/kiota-http-guzzle with Composer so generated SDKs can send requests to API endpoints, with middleware and auth handled for you.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package in your Laravel project:

    composer require microsoft/kiota-http-guzzle
    

    Ensure your composer.json requires Guzzle HTTP (^7.4.5 or higher).

  2. Generate a Kiota client (if not already done): Use the Kiota CLI or manually scaffold a client from OpenAPI/Swagger specs.

  3. Configure the HTTP adapter:

    use Microsoft\Kiota\Abstractions\Http\IHttpRequestAdapter;
    use Microsoft\Kiota\Http\Guzzle\GuzzleHttpRequestAdapter;
    
    $adapter = new GuzzleHttpRequestAdapter();
    $client = new YourGeneratedClient($adapter);
    
  4. First API call:

    $response = $client->getGroups()->get();
    $groups = $response->getValue();
    

Key Entry Points

  • GuzzleHttpRequestAdapter: Core class for HTTP requests.
  • Middleware stack: Extend with custom handlers (e.g., auth, logging).
  • Error handling: Built-in ApiException for HTTP errors.

Implementation Patterns

1. Middleware Integration

Leverage Kiota’s middleware stack to customize requests/responses. Example: Add an auth middleware:

use Microsoft\Kiota\Abstractions\Http\IHttpPipelinePolicy;
use Microsoft\Kiota\Http\Guzzle\GuzzleHttpRequestAdapter;
use GuzzleHttp\Psr7\Request;

class BearerTokenPolicy implements IHttpPipelinePolicy
{
    public function __construct(private string $token) {}

    public function beforeSendRequest(Request $request): Request
    {
        return $request->withHeader('Authorization', 'Bearer ' . $this->token);
    }
}

// Usage:
$adapter = new GuzzleHttpRequestAdapter();
$adapter->addPolicy(new BearerTokenPolicy('your-token-here'));

2. Guzzle Client Customization

Pass a custom Guzzle client to the adapter:

use GuzzleHttp\Client;

$guzzleClient = new Client([
    'base_uri' => 'https://api.example.com',
    'timeout'  => 10.0,
]);

$adapter = new GuzzleHttpRequestAdapter($guzzleClient);

3. Async/Await Support

Use sendAsync() for non-blocking calls (requires PHP 8.1+):

$promise = $client->getGroups()->getAsync();
$response = $promise->wait();

4. Error Handling

Catch ApiException for HTTP errors:

try {
    $response = $client->getGroups()->get();
} catch (ApiException $e) {
    // Access raw response headers/body via $e->getResponse()
    logger()->error('API Error:', ['status' => $e->getStatusCode()]);
}

5. Headers Inspection

Enable debug headers (requires HeadersInspectionHandler):

$adapter->addPolicy(new HeadersInspectionHandler());

Gotchas and Tips

Pitfalls

  1. PHP Version Requirement:

    • Minimum PHP 8.2 (since v2.0.0). Older versions (7.2–8.1) are unsupported.
    • Fix: Update your Laravel project’s PHP version or use v1.x of the package.
  2. Guzzle Version Lock:

    • The package enforces Guzzle HTTP ^7.4.5. Mismatches may cause runtime errors.
    • Fix: Pin Guzzle in composer.json:
      "guzzlehttp/guzzle": "^7.4.5"
      
  3. Query Parameter Decoding:

    • The parameterNamesDecodingHandler only decodes parameter names, not values.
    • Workaround: Manually encode values before passing to Kiota.
  4. Empty 2xx Responses:

    • Some APIs return 2xx without a body (e.g., DELETE requests). Kiota handles this, but Laravel’s HTTP clients may not.
    • Tip: Use sendAsync() to inspect raw responses if needed.
  5. Middleware Order Matters:

    • Policies run in registration order. Place auth middleware first to avoid bypassing it.

Debugging Tips

  • Enable Guzzle Debug:
    $guzzleClient = new Client(['debug' => fopen('guzzle.log', 'w+')]);
    
  • Inspect Headers: Use HeadersInspectionHandler to log raw headers:
    $adapter->addPolicy(new HeadersInspectionHandler());
    
  • Check Response Bodies: For empty responses, use:
    $response = $client->getGroups()->getAsync()->wait();
    $body = $response->getBody(); // Raw response body
    

Extension Points

  1. Custom Error Mapping: Override ApiException behavior by extending ErrorMappingHandler:

    use Microsoft\Kiota\Http\Guzzle\Handlers\ErrorMappingHandler;
    
    class CustomErrorHandler extends ErrorMappingHandler
    {
        protected function getErrorMapping(): array
        {
            return [
                '401' => new CustomUnauthorizedException(),
                // ...
            ];
        }
    }
    
  2. Tracing Support: Integrate with OpenTelemetry:

    use Microsoft\Kiota\Http\Guzzle\Handlers\TracingHandler;
    
    $adapter->addPolicy(new TracingHandler());
    
  3. Retry Logic: Use Guzzle’s retry middleware:

    $guzzleClient = new Client([
        'handler' => HandlerStack::create([
            new RetryMiddleware([
                'max_retries' => 3,
                'delay'       => 100,
            ]),
        ]),
    ]);
    

Laravel-Specific Quirks

  • Service Container Binding: Bind the adapter in AppServiceProvider:
    $this->app->bind(IHttpRequestAdapter::class, function ($app) {
        return new GuzzleHttpRequestAdapter(
            new Client(['base_uri' => config('services.api.base_uri')])
        );
    });
    
  • Caching Responses: Use Laravel’s cache middleware with Guzzle:
    $guzzleClient = new Client([
        'on_stats' => function (TransferStats $stats) {
            Cache::put("api_{$stats->getHandler()->getUri()}", $stats->getBody(), now()->addMinutes(5));
        },
    ]);
    
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.
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names