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

microsoft/kiota-abstractions

The Kiota Abstractions Library for PHP provides the core constructs and interfaces needed by Kiota-generated SDKs from OpenAPI definitions. Add it via composer require microsoft/kiota-abstractions to build and run generated API clients.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require microsoft/kiota-abstractions

This package is a dependency for Kiota-generated SDKs, so you typically won’t use it directly unless extending or customizing Kiota functionality.

  1. First Use Case:

    • If you’re working with a Kiota-generated SDK (e.g., from OpenAPI/Swagger), this package provides the core abstractions for:
      • Request/Response Handling (RequestInformation, ApiException).
      • Model Serialization/Deserialization (BackedModel, ParseNode).
      • Authentication (AccessTokenProvider).
      • HTTP Adapters (RequestAdapter).
    • Example: Customizing a request before sending:
      use Microsoft\Kiota\Abstractions\RequestInformation;
      use Microsoft\Kiota\Abstractions\RequestAdapter;
      
      $requestInfo = new RequestInformation();
      $requestInfo->method = 'GET';
      $requestInfo->urlTemplate = 'https://api.example.com/users/{id}';
      $requestInfo->pathParameters = ['id' => '123'];
      
      $adapter = new RequestAdapter();
      $response = $adapter->sendAsync($requestInfo)->wait();
      
  2. Key Classes to Explore:

    • RequestInformation: Core request metadata (headers, body, URL templates).
    • BackedModel: Base class for generated models (handles serialization/deserialization).
    • ApiException: Standardized error handling for API responses.
    • RequestAdapter: Interface for HTTP clients (e.g., Guzzle, Symfony HTTP Client).

Implementation Patterns

1. Customizing Requests/Responses

  • Override Default Headers:
    $requestInfo = new RequestInformation();
    $requestInfo->headers->add('X-Custom-Header', 'value');
    $requestInfo->headers->tryAdd('X-Idempotency', 'unique-id'); // Safe add (no overwrite)
    
  • Stream Content:
    $requestInfo->setStreamContent(
        fopen('file.txt', 'r'),
        'application/octet-stream' // Defaults to this if omitted
    );
    

2. Handling Models

  • Extend BackedModel for custom logic:
    use Microsoft\Kiota\Abstractions\BackedModel;
    
    class CustomUser extends BackedModel {
        public string $name;
        public int $age;
    
        protected function getFieldDeserializers(): array {
            return [
                'name' => fn($value) => $value,
                'age'  => fn($value) => (int)$value,
            ];
        }
    }
    
  • Nested Models: Kiota automatically handles nested objects/arrays. Modify a nested property to mark the parent as "dirty" (requires re-serialization):
    $user = new CustomUser();
    $user->address->city = 'New York'; // Triggers dirty state
    

3. Authentication

  • Implement AccessTokenProvider for OAuth/JWT:
    use Microsoft\Kiota\Abstractions\AccessTokenProvider;
    
    class MyTokenProvider implements AccessTokenProvider {
        public function getAuthorizationTokenAsync(): ?string {
            return 'Bearer ' . $this->fetchToken();
        }
    }
    
  • Attach to a request:
    $requestInfo->accessTokenProvider = new MyTokenProvider();
    

4. HTTP Adapters

  • Replace Default Adapter (e.g., for Guzzle):
    use Microsoft\Kiota\Abstractions\RequestAdapter;
    use GuzzleHttp\Client;
    
    class GuzzleAdapter implements RequestAdapter {
        private Client $client;
    
        public function sendAsync(RequestInformation $requestInfo): Promise {
            return new Promise(fn() => $this->client->request(
                $requestInfo->method,
                $requestInfo->url,
                [
                    'headers' => $requestInfo->headers->toArray(),
                    'body'    => $requestInfo->body,
                ]
            ));
        }
    }
    

5. Error Handling

  • Catch ApiException for HTTP errors:
    try {
        $response = $adapter->sendAsync($requestInfo)->wait();
    } catch (ApiException $e) {
        // Access status code, headers, or body
        $status = $e->statusCode;
        $headers = $e->headers;
    }
    

6. Observability

  • Integrate OpenTelemetry for tracing:
    use Microsoft\Kiota\Abstractions\Observability\Telemetry;
    
    Telemetry::setTracerProvider($tracerProvider);
    

7. URL Templates

  • Use std-uritemplate for dynamic URLs:
    $requestInfo->urlTemplate = '/users/{id}/posts/{postId}';
    $requestInfo->pathParameters = ['id' => '1', 'postId' => '42'];
    // Resolves to: /users/1/posts/42
    

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 project or use an older Kiota version (e.g., ^1.5.0).
  2. Nullability:

    • Methods like AccessTokenProvider::getAuthorizationTokenAsync() return ?string. Always handle null:
      $token = $provider->getAuthorizationTokenAsync();
      if ($token === null) {
          throw new RuntimeException('Token provider failed');
      }
      
  3. Dirty State in Nested Models:

    • Modifying a nested BackedModel or array of models marks the entire parent model as dirty. Avoid deep nesting if performance is critical.
  4. Header Case Sensitivity:

    • Headers are case-insensitive by default. Use tryAdd() to avoid overwriting existing headers accidentally.
  5. Deprecated Methods:

    • ApiException::getResponse() was removed in v0.6.0. Use statusCode, headers, or body directly.
  6. Stream Content Defaults:

    • setStreamContent() defaults to application/octet-stream. Specify explicitly for non-binary data (e.g., text/plain).
  7. OpenTelemetry Auto-Suggestion:

    • Disabled in v0.8.5 to avoid conflicts with PSR-15 implementations. Manually configure if needed.

Debugging Tips

  1. Inspect Requests:

    • Log RequestInformation before sending:
      var_dump($requestInfo->url, $requestInfo->headers->toArray(), $requestInfo->body);
      
  2. Validate Models:

    • Use BackedModel::validate() to check deserialized data:
      if (!$model->validate()) {
          throw new InvalidArgumentException('Model validation failed');
      }
      
  3. URL Template Errors:

    • Ensure pathParameters match the template exactly (e.g., {id} vs. {userId}).
  4. Async Promises:

    • Use ->wait() for synchronous code or then() for async:
      $adapter->sendAsync($requestInfo)
          ->then(fn($response) => $response->body)
          ->otherwise(fn($e) => error_log($e->getMessage()));
      

Extension Points

  1. Custom Serializers/Deserializers:

    • Override getFieldSerializers()/getFieldDeserializers() in BackedModel subclasses.
  2. Request Middleware:

    • Wrap RequestAdapter to add logging, retries, or auth:
      class LoggingAdapter implements RequestAdapter {
          private RequestAdapter $delegate;
      
          public function sendAsync(RequestInformation $requestInfo): Promise {
              error_log('Sending request to: ' . $requestInfo->url);
              return $this->delegate->sendAsync($requestInfo);
          }
      }
      
  3. Composed Types:

    • Mark custom composed types with ComposedTypeWrapper for proper deserialization.
  4. Date/Time Handling:

    • Use helper traits (DateTimeHelper, DateIntervalHelper) for ISO 8601 parsing/formatting.
  5. Multipart Requests:

    • Leverage RequestInformation::setMultipartContent() for file uploads:
      $requestInfo->setMultipartContent([
          'file' => new \CURLFile('path/to/file'),
          'data' => 'value',
      ]);
      

Config Quirks

  1. Backing Store Factory:

    • Singleton (BackingStoreFactorySingleton) is non-nullable since v0.6.0. No need to check for null.
  2. Default Content Types:

    • setStreamContent() defaults to application/octet-stream. Override if needed (e.g
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.
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
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings