Howard
Howard

Reputation: 3758

How to run cURL via guzzle

First time using cURL and guzzle. This is probably a simple question but would appreciate a "helloworld" example.

This is the cURL I currently have:

curl --include --request POST \
--header "application/x-www-form-urlencoded" \
--header "X-Access-Token: ACCESS_TOKEN" \
--data-binary "grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY" \
'https://api.url.com/token'

And this is the guzzle code:

$client = new Client(); //GuzzleHttp\Client
$result = $client->post('https://api.url.com/token', [
    'form_params' => [
        'sample-form-data' => 'value'
    ]
]);

I'm not sure how to run the cURL command using guzzle. How would the resulting guzzle code look like?

Upvotes: 2

Views: 10612

Answers (3)

Tobias K.
Tobias K.

Reputation: 3092

Sorry for the late answer, I see you already found a solution yourself. While it works, it's not the Guzzle way / "best practise" to manually code your body payload like that.

Guzzle provides a cleaner way for that, and builds the body-payload internally:

$result = $client->post('https://api.url.com/token', [
  'headers' => ['X-Access-Token' => 'ACCESS_TOKEN'],
  'form_params' => [
    'grant_type' => 'client_credentials',
    'client_id' => 'PUBLIC_KEY',
    'client_secret' => 'PRIVATE_KEY',
  ],
]);

Correct concatenation with ?/& aswell as adding the application/x-www-form-urlencoded is done by Guzzle automatically. This is the request that is sent off by the above code:

POST /token HTTP/1.1
Content-Length: 76
User-Agent: GuzzleHttp/6.3.3 curl/7.57.0 PHP/7.2.2
Content-Type: application/x-www-form-urlencoded
Host: api.url.com
X-Access-Token: ACCESS_TOKEN

grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY

Upvotes: 3

Howard
Howard

Reputation: 3758

So here's the answer for converting cURL to Guzzle. Maybe it will help future people that need a "helloworld" like I did. This is how I ran the cURL in PHP via Guzzle:

$client = new Client();
$uri = 'https://api.url.com/token';
$headers = [
    'Content-Type' => 'application/x-www-form-urlencoded',
    'X-Access-Token' => $ACCESS_TOKEN
];
$body = 'grant_type=client_credentials&client_id='.$PUBLIC_KEY.'&client_secret='.$PRIVATE_KEY;
$result = $client->request('POST', $uri, [
    'headers' => $headers,
    'body' => $body
]);

json_decode($result->getBody()->getContents(), true);

Two things that weren't intuitive was you have to designate 'application/x-www-form-urlencoded' as Content-Type. And 'data-binary' as 'body'.

Upvotes: 2

Abdullah Aman
Abdullah Aman

Reputation: 1620

You can get/see the result of your Guzzle call by calling the "getBody" function. In your case, $result->getBody()

Upvotes: 0

Related Questions