Search code examples
phprestcurlguzzleguzzle6

Issue converting from cURL to Guzzle 6 with JSON and XML file


I am having a hard time converting cURL to Guzzle6. I'm want to send a name and reference UUID via JSON AND the contents of an XML file to process to a REST endpoint.

cURL

curl -H 'Expect:' -F 
'request={"name":"test", "reference":"870e0320-021e-4c67-9169-d4b2c7e5b9c9"}' 
-F '[email protected]' http://ec2-48-88-173-9.us-east-1.compute.amazonaws.com:8180/rs/process

Guzzle

$client = new Client(['debug' => true]);

$request = $client->request('POST',
    'http://ec2-48-88-173-9.us-east-1.compute.amazonaws.com:8180/rs/process', [
        'multipart' => [
            [
                'name' => 'data',
                'contents' => "{'name':'test','reference':870e0320-021e-4c67-9169-d4b2c7e5b9c9}",
                'headers' => ['Content-Type' => 'application/json']
            ],
            [
                'name' => 'file',
                'contents' => fopen('sample.xml', 'r'),
                'headers' => ['Content-Type' => 'text/xml']
            ],
        ]
    ]
);

$response = $request->getBody()->getContents();

Also, I'm not sure what the 'name' fields should be ('name' => 'data'), etc.


Solution

  • This is the Guzzle equivalent of your curl command:

    $client = new Client(['debug' => true]);
    
    $request = $client->request('POST',
        'http://ec2-48-88-173-9.us-east-1.compute.amazonaws.com:8180/rs/process', [
            'multipart' => [
                [
                    'name' => 'request',
                    'contents' => "{'name':'test','reference':870e0320-021e-4c67-9169-d4b2c7e5b9c9}",
                ],
                [
                    'name' => 'file',
                    'contents' => fopen('sample.xml', 'r'),
                ],
            ]
        ]
    );
    
    $response = $request->getBody()->getContents();
    

    For the file Guzzle will specify the appropriate content type, as curl does. Name for the first part is request — from -F 'request={"name":"test", "reference":"870e0320-021e-4c67-9169-d4b2c7e5b9c9"}'