Bug
Bug

Reputation: 501

Can't set Guzzle Content Type

I'm trying to request this way:

$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';

$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers'  => ['content-type' => 'application/json', 'Accept' => 'application/json'],
    'defaults' => [
         'auth' => [$publishable_key, ''],
],
    'body' => json_encode($body),
]);

The problem is that this request is being set without Content-Type. What am I doing wrong?

Upvotes: 11

Views: 35200

Answers (3)

Bruno Leveque
Bruno Leveque

Reputation: 2811

I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.

I fixed it this way

$client = new Client([
    'base_uri' => 'https://api.hubapi.com/',
    'timeout'  => 5,
    'headers' => ['Content-Type' => 'application/json']
]);

And then performing my requests the regular way

try
{
    $response = $client->request('POST', '/contacts/v1/contact/email/[email protected]/profile',
    ['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }

I hope this helps.

Upvotes: 2

Mick
Mick

Reputation: 31949

Guzzle 6

Guzzle will set the Content-Type header to application/x-www-form-urlencoded when no Content-Type header is already present.

You have 2 options.

Option 1: On the Client directly

$client = new GuzzleHttp\Client(
    ['headers' => [
        'Content-Type' => 'application/json'
        ]
    ]
);

Option 2: On a Per Request basis

// Set various headers on a request
$client = new GuzzleHttp\Client();

$client->request('GET', '/whatever', [
    'headers' => [
        'Content-Type' => 'application/json'
    ]
]);

You can refer to Guzzle 6: Request Options

Upvotes: 14

Bug
Bug

Reputation: 501

Ok .. the problem was that I was setting body and headers outside of defautls. the solution is:

$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'defaults' => [
     'auth' => [$publishable_key, ''],
     'headers'  => ['content-type' => 'application/json', 'Accept' => 'application/json'],
     'body' => json_encode($body),
],
]);

Upvotes: 17

Related Questions