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.

13 comments

@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'] // or 'json' => [...]
]);

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.

@Sevenearths 2019-03-13 12:03:38

I was looking around for an hour for this answer. Why is this not in the documentation (especially the quick setup guide)? Crazy!?!

@giovannipds 2019-12-11 16:46:53

According to docs now, you can just use what @davykiash said, 'json' => $data: stackoverflow.com/a/44154428/842768

@Michal Gallovic 2020-02-08 20:53:06

@giovannipds GuzzleHttp\RequestOptions::JSON is an alias to 'json', either is fine.

@Tebe 2020-02-10 12:55:27

doesnt work for guzzle 6.3

@Michal Gallovic 2020-02-11 08:54:30

@Tebe tried with Guzzle ^6.3 and it works with json string as well as constant.

@Tebe 2020-02-11 10:11:27

just replaced library, much less hasssles , recommending this github.com/rmccue/Requests . what e mess it should be if sending simple post request take s a whole discussion

@Tuncay Elvanağaç 2019-12-20 08:31:21

Php Version: 5.6

Symfony version: 2.3

Guzzle: 5.0

I had an experience recently about sending json with Guzzle. I use Symfony 2.3 so my guzzle version can be a little older.

I will also show how to use debug mode and you can see the request before sending it,

When i made the request as shown below got the successfull response;

use GuzzleHttp\Client;

$headers = [
        'Authorization' => 'Bearer ' . $token,        
        'Accept'        => 'application/json',
        "Content-Type"  => "application/json"
    ];        

    $body = json_encode($requestBody);

    $client = new Client();    

    $client->setDefaultOption('headers', $headers);
    $client->setDefaultOption('verify', false);
    $client->setDefaultOption('debug', true);

    $response = $client->post($endPoint, array('body'=> $body));

    dump($response->getBody()->getContents());

@Nurul Huda 2019-06-30 09:54:05

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    'json' => ['foo' => 'bar']
]);

See Docs.

@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();

@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;

@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']]);

@Hanane 2019-09-30 14:42:30

I have tried this with Guzzle3 is not working even if it is the way mentionned in the doc : guzzle3.readthedocs.io/http-client/… , it's been 2 days I am trying to solve this pb but in vain

@giovannipds 2019-12-11 16:47:07

According to docs now, you can just use what @davykiash said, 'json' => $data: stackoverflow.com/a/44154428/842768

@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

@vietnguyen09 2019-06-26 02:50:43

This answer works for me when the accepted answer doesn't.

@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.

@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

28 Answered Questions

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

18 Answered Questions

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

13 Answered Questions

[SOLVED] How do I send a POST request with PHP?

  • 2011-04-13 10:06:00
  • Fred Tanrikut
  • 983195 View
  • 653 Score
  • 13 Answer
  • Tags:   php http post request

6 Answered Questions

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

  • 2015-05-29 12:53:19
  • rap-2-h
  • 96689 View
  • 169 Score
  • 6 Answer
  • Tags:   php guzzle

3 Answered Questions

[SOLVED] Using Guzzle to send POST request with JSON

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

1 Answered Questions

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

1 Answered Questions

How can I use Guzzle to send a PUT request?

1 Answered Questions

How to Wrap guzzle json post body in array

  • 2019-03-21 01:22:43
  • Chris Hudson
  • 299 View
  • 0 Score
  • 1 Answer
  • Tags:   laravel guzzle

5 Answered Questions

[SOLVED] Send POST data via raw json with postman

  • 2016-08-18 00:09:20
  • Dallas
  • 276874 View
  • 104 Score
  • 5 Answer
  • Tags:   php json rest postman

2 Answered Questions

Sponsored Content