Bill Garrison
Bill Garrison

Reputation: 2237

Curl to GuzzleHttp request

I have been given the following curl request:

curl -H "Content-Type:application/json" -H "Api-Key:someapikey" -X -d {"address":"30598 West Street","city":"Oakdale"}' PUT "https://somedomain/api/members/1234567"

I am trying to replicate this with GuzzleHttp like so:

$headers = [
    'Api-Key'      => $this->apiKey,
    'Content-Type' => 'application/json',
];
$client = new Client([
    'headers' => $headers,
]);
$res = $client->put("{$this->baseUrl}/members/{$fields['vip_id']}", [
    'form_params' => $fields,
]);

I keep on getting a 415 Unsupported Media Type response. From the curl I was given I think I have all my bases covered. However, when I debug it shows that my Content Type is set to application/x-www-form-urlencoded. According to the documentation, the header is set to this only if the Content-Type header isn't already set and form_params is included. As I am already setting this header, it shouldn't be switching right? Please help!

Upvotes: 1

Views: 1113

Answers (1)

drew010
drew010

Reputation: 69977

The reason your headers are being overridden is because the form_params option to the request is specifically for sending x-www-form-urlencoded data.

You can omit the Content-Type header from your options completely and instead use the json key in the request to send JSON data.

$headers = [
    'Api-Key'      => $this->apiKey,
];
$client = new Client([
    'headers' => $headers,
]);
$res = $client->put("{$this->baseUrl}/members/{$fields['vip_id']}", [
    'json' => $fields, // causes Guzzle to set content type to application/json
                       // and json_encode your $fields
]);

Upvotes: 2

Related Questions