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.
Installation Add the package via Composer:
composer require microsoft/kiota-serialization-multipart
Ensure your composer.json includes the package under require.
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.
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);
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");
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
}
}
Custom Headers Set custom headers for multipart requests:
$requestInfo->setHeader("Content-Type", "multipart/form-data");
$requestInfo->setHeader("X-Custom-Header", "value");
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"));
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
Memory Management Large files can consume significant memory. Stream files directly to the request body instead of loading them entirely into memory.
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());
Boundary Conflicts Ensure the boundary string used in multipart requests does not conflict with data content. The library generates a unique boundary by default.
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.
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";
}
}
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);
}
}
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"
]);
How can I help you explore Laravel packages today?