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

Kiota Serialization Multipart Laravel Package

microsoft/kiota-serialization-multipart

PHP multipart body serialization library for Microsoft Kiota-generated clients. Provides multipart payload handling so SDKs can send/receive multipart requests and responses. Install via Composer: microsoft/kiota-serialization-multipart.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require microsoft/kiota-serialization-multipart
    

    Ensure your composer.json includes the package under require.

  2. Kiota Integration This package is designed for use with Kiota. If you haven’t already, generate a Kiota client for your API using the Kiota CLI or the Kiota Codegen.

  3. First Use Case: Uploading a File Use the MultipartSerializer to handle file uploads in multipart requests. Example:

    use Microsoft\Kiota\Serialization\Multipart\MultipartSerializer;
    use Microsoft\Kiota\Serialization\Multipart\MultipartSerializerBuilder;
    
    $serializer = MultipartSerializerBuilder::create()
        ->withTypeMapper(new YourCustomTypeMapper())
        ->build();
    
    $requestInfo = new RequestInformation();
    $requestInfo->setMethod("POST");
    $requestInfo->setUrl("https://api.example.com/upload");
    
    $bodyContent = new MultipartBodyContent();
    $bodyContent->addFile("file", "/path/to/file.txt", "text/plain");
    
    $serializer->serialize($requestInfo, $bodyContent);
    

Implementation Patterns

Workflows

  1. File Uploads Use MultipartBodyContent to construct requests with files:

    $bodyContent = new MultipartBodyContent();
    $bodyContent->addFile("file", fopen("/path/to/file.pdf", "r"), "application/pdf");
    $bodyContent->addText("description", "Monthly report");
    
  2. Complex Objects Serialize complex objects by implementing IParseable and ISerializable:

    class MyModel implements IParseable, ISerializable {
        public function serializeContent(): string {
            return json_encode($this->toArray());
        }
    
        public function parseContent(string $content): void {
            $data = json_decode($content, true);
            // Populate object properties
        }
    }
    
  3. Custom Headers Set custom headers for multipart requests:

    $requestInfo->setHeader("Content-Type", "multipart/form-data");
    $requestInfo->setHeader("X-Custom-Header", "value");
    

Integration Tips

  • Kiota Client Configuration Configure your Kiota client to use the MultipartSerializer:

    $client = new YourApiClient(
        new RequestAdapter(
            new HttpClient(),
            new MultipartSerializer()
        )
    );
    
  • Error Handling Wrap serialization in try-catch blocks to handle potential exceptions:

    try {
        $serializer->serialize($requestInfo, $bodyContent);
    } catch (SerializationException $e) {
        Log::error("Serialization failed: " . $e->getMessage());
    }
    
  • Testing Use MultipartSerializer in unit tests to mock multipart requests:

    $serializer = new MultipartSerializer();
    $requestInfo = new RequestInformation();
    $bodyContent = new MultipartBodyContent();
    $serializer->serialize($requestInfo, $bodyContent);
    
    $this->assertEquals("multipart/form-data", $requestInfo->getHeader("Content-Type"));
    

Gotchas and Tips

Pitfalls

  1. File Handling Ensure files are properly closed after adding to MultipartBodyContent. Use fopen with explicit file handles:

    $fileHandle = fopen("/path/to/file.txt", "r");
    $bodyContent->addFile("file", $fileHandle, "text/plain");
    fclose($fileHandle); // Close the file handle after adding
    
  2. Memory Management Large files can consume significant memory. Stream files directly to the request body instead of loading them entirely into memory.

  3. Content-Type Headers Forgetting to set Content-Type: multipart/form-data will result in serialization errors. Always include this header:

    $requestInfo->setHeader("Content-Type", "multipart/form-data; boundary=" . $serializer->getBoundary());
    
  4. Boundary Conflicts Ensure the boundary string used in multipart requests does not conflict with data content. The library generates a unique boundary by default.

Debugging

  • Log Serialized Output Log the serialized request body for debugging:

    $serializedBody = $serializer->serialize($requestInfo, $bodyContent);
    Log::debug("Serialized Body: " . $serializedBody);
    
  • Check for Malformed Data Validate that all parts of the multipart body are correctly formatted. Use tools like Postman or curl to inspect requests.

Extension Points

  1. Custom Type Mappers Extend functionality by implementing a custom TypeMapper:

    class CustomTypeMapper implements ITypeMapper {
        public function mapType($type): string {
            // Custom logic to map types
            return "application/json";
        }
    }
    
  2. Custom Serializers Create custom serializers for specific use cases by extending MultipartSerializer:

    class CustomMultipartSerializer extends MultipartSerializer {
        public function serialize(RequestInformation $requestInfo, IParseable $parseable): string {
            // Custom serialization logic
            return parent::serialize($requestInfo, $parseable);
        }
    }
    
  3. Integration with Laravel HTTP Client Use the MultipartSerializer with Laravel’s HTTP client for seamless integration:

    $serializer = new MultipartSerializer();
    $requestInfo = new RequestInformation();
    $bodyContent = new MultipartBodyContent();
    
    $serializer->serialize($requestInfo, $bodyContent);
    
    $response = Http::withHeaders($requestInfo->getHeaders())
        ->asForm()->post("https://api.example.com/upload", [
            'file' => fopen("/path/to/file.txt", "r"),
            'description' => "Monthly report"
        ]);
    
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