By user3379466


2014-03-07 08:06:37 8 Comments

Does anybody know the correct way to post JSON using Guzzle?

$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'
        ),array(json_encode($_POST)));

I get an internal server error response from the server. It works using Chrome Postman.

11 comments

@Yamen Ashraf 2018-11-07 09:32:13

$client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']);

$response = $client->post('/save', [
    'json' => [
        'name' => 'John Doe'
    ]
]);

return $response->getBody();

@Michal Gallovic 2015-04-13 09:21:15

For Guzzle 5 & 6 you do it like this:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']
]);

Docs

@Pierre de LESPINAY 2015-09-10 12:27:59

This is the right way to do (official example here)

@robsch 2017-01-04 15:44:58

According to doc magic methods can be used. So post() should work.

@ksadowski 2017-03-22 12:02:07

It's recommended to use RequestOptions constants for the options array keys (GuzzleHttp\RequestOptions::JSON in this case) - it makes typos easier to detect as they suddenly become notices instead of just silent bugs waiting to cause trouble.

@Michal Gallovic 2017-03-22 17:38:57

@ksadowski Can you share docs with this info ? In github.com/guzzle/guzzle/blob/master/src/… RequestOptions::JSON is a constant with "json" - so it should be the same.

@zessx 2017-11-02 16:54:38

@MichalGallovic It is the same. The purpose to use the constant is to avoid typos. Using a constant that does not exists will raise an error, but sending a useless option (as jsson for example) won't raise any error, and you may take some time to find your typo.

@Michal Gallovic 2018-02-03 18:31:00

That makes sense, thanks.

@user5948411 2017-11-16 10:57:42

Simply use this it will work

   $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();

@davykiash 2017-05-24 09:30:28

This worked for me (using Guzzle 6)

$client = new Client(); 
$result = $client->post('http://api.example.com', [
            'json' => [
                'value_1' => 'number1',
                'Value_group' =>  
                             array("value_2" => "number2",
                                    "value_3" => "number3")
                    ]
                ]);

echo($result->getBody()->getContents());

@user3379466 2014-03-07 08:56:21

For Guzzle <= 4:

It's a raw post request so putting the JSON in the body solved the problem

$request = $this->client->post($url,array(
                'content-type' => 'application/json'
        ),array());
$request->setBody($data); #set body!
$response = $request->send();

return $response;

@Raúl Ferràs 2014-06-17 14:16:15

is $data already encoded into json?

@Layke 2015-04-22 20:13:03

Yes it is @RaúlFerràs

@hbt 2015-04-22 20:13:18

This no longer works with GuzzleHttp. @Charlie has the right answer

@Fabrice Kabongo 2017-04-05 08:52:53

I think we just need to specify the version of Guzzle in the question.

@marcovtwout 2017-04-13 06:41:47

If you want to set the content type header in Guzzle 6, you can do it like this: $client->post($url, ['body' => $string, 'headers' => ['Content-type' => 'application/json']]);

@arcos.lwm 2016-12-26 20:48:07

This works for me with Guzzle 6.2 :

$gClient =  new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
                            array(
                                'headers'=>array('Content-Type'=>'application/json'),
                                'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
                                )
                    );

According to the documentation guzzle do the json_encode

@Suraj 2016-11-30 12:07:22

Above answers did not worked for me somehow. But this works fine for me.

 $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

 $request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));

@Frank Roth 2016-09-16 06:30:23

The simple and basic way (guzzle6):

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

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';

@Faisal Sarfraz 2017-06-07 06:50:36

This is really one simple and easy way. Solved my problem about setting body and headers. Thanks very much

@Dung 2016-01-21 23:10:53

@user3379466 is correct, but here I rewrite in full:

-package that you need:

 "require": {
    "php"  : ">=5.3.9",
    "guzzlehttp/guzzle": "^3.8"
},

-php code (Digest is a type so pick different type if you need to, i have to include api server for authentication in this paragraph, some does not need to authenticate. If you use json you will need to replace any text 'xml' with 'json' and the data below should be a json string too):

$client = new Client('https://api.yourbaseapiserver.com/incidents.xml', array('version' => 'v1.3', 'request.options' => array('headers' => array('Accept' => 'application/vnd.yourbaseapiserver.v1.1+xml', 'Content-Type' => 'text/xml'), 'auth' => array('[email protected]', 'password', 'Digest'),)));

$url          = "https://api.yourbaseapiserver.com/incidents.xml";
        
$data = '<incident>
<name>Incident Title2a</name>
<priority>Medium</priority>
<requester><email>[email protected]</email></requester>
<description>description2a</description>
</incident>';

    $request = $client->post($url, array('content-type' => 'application/xml',));

    $request->setBody($data); #set body! this is body of request object and not a body field in the header section so don't be confused.

    $response = $request->send(); #you must do send() method!
    echo $response->getBody(); #you should see the response body from the server on success
    die;

--- Solution for * Guzzle 6 * --- -package that you need:

 "require": {
    "php"  : ">=5.5.0",
    "guzzlehttp/guzzle": "~6.0"
},

$client = new Client([
                             // Base URI is used with relative requests
                             'base_uri' => 'https://api.compay.com/',
                             // You can set any number of default request options.
                             'timeout'  => 3.0,
                             'auth'     => array('[email protected]', 'dsfddfdfpassword', 'Digest'),
                             'headers' => array('Accept'        => 'application/vnd.comay.v1.1+xml',
                                                'Content-Type'  => 'text/xml'),
                         ]);

$url = "https://api.compay.com/cases.xml";
    $data string variable is defined same as above.


    // Provide the body as a string.
    $r = $client->request('POST', $url, [
        'body' => $data
    ]);

    echo $r->getBody();
    die;

@j boschiero 2014-07-17 23:44:02

The answer from @user3379466 can be made to work by setting $data as follows:

$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):

$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:

echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.

@phpisuber01 2014-10-30 20:33:13

Just a heads up... you can simplify your $data by using json_encode: $data = json_encode(array('collection' => $existing_variable));

@CharlieJade 2014-12-30 15:35:48

$client = new \GuzzleHttp\Client();

$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;

$res = $client->post($url, [ 'body' => json_encode($body) ]);

$code = $res->getStatusCode();
$result = $res->json();

@Ja͢ck 2015-06-16 08:54:49

Does this also set the correct header? I think ['json' => $body] is the better way here, as mentioned by Michael's answer.

@fegyi001 2016-03-29 11:46:31

This is the right answer, thanks @Charlie!

@David 2016-03-29 15:41:26

$res->json(); only works in Guzzle 5.3. It's been removed in v6.

@Andreas 2016-05-16 08:40:08

David is correct. This is because of PSR-7 implementation. Use json_decode() instead.

Related Questions

Sponsored Content

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

28 Answered Questions

[SOLVED] How can I prevent SQL injection in PHP?

1 Answered Questions

[SOLVED] POST Request works with Postman, but not with Guzzle

5 Answered Questions

[SOLVED] Guzzle 6: no more json() method for responses

  • 2015-05-29 12:53:19
  • rap-2-h
  • 62359 View
  • 132 Score
  • 5 Answer
  • Tags:   php guzzle

2 Answered Questions

[SOLVED] Using Guzzle to send POST request with JSON

  • 2017-09-24 07:31:46
  • Kira
  • 2133 View
  • 0 Score
  • 2 Answer
  • Tags:   php laravel guzzle

1 Answered Questions

[SOLVED] unable to send json as guzzle post body

0 Answered Questions

Sending form params as body for Guzzle POST request

2 Answered Questions

1 Answered Questions

[SOLVED] POST request with files and fields in guzzle

2 Answered Questions

[SOLVED] guzzle ver 6 post method is not woking

  • 2015-06-16 06:28:03
  • RahulG
  • 2372 View
  • 3 Score
  • 2 Answer
  • Tags:   php guzzle

Sponsored Content