[php] PHP GuzzleHttp. How to make a post request with params?

How to make a post request with GuzzleHttp( version 5.0 ).

I am trying to do the following:

$client = new \GuzzleHttp\Client();
$client->post(
    'http://www.example.com/user/create',
    array(
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword'
    )
);

But I am getting the error:

PHP Fatal error: Uncaught exception 'InvalidArgumentException' with the message 'No method can handle the email config key'

This question is related to php request httpclient guzzle

The answer is


$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file


Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);

Request with POST files

$response = $client->request('POST', 'http://www.example.com/files/post', [
    'multipart' => [
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'csv_header',
            'contents' => 'First Name, Last Name, Username',
            'filename' => 'csv_header.csv'
        ]
    ]
]);

REST verbs usage with params

// PUT
$client->put('http://www.example.com/user/4', [
    'body' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    'timeout' => 5
]);

// DELETE
$client->delete('http://www.example.com/user');

Async POST data

Usefull for long server operations.

$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);
$promise->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);

Set headers

According to documentation, you can set headers :

// Set various headers on a request
$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ]
]);

More information for debugging

If you want more details information, you can use debug option like this :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    // If you want more informations during request
    'debug' => true
]);

Documentation is more explicits about new possibilities.


Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.

Incorrect:

$response = $client->post('http://example.com/api', [
    'body' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'json' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',
    ])
])

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to request

How to send Basic Auth with axios How to post raw body data with curl? Pandas read_csv from url POST request with a simple string in body with Alamofire PHP GuzzleHttp. How to make a post request with params? How to modify the nodejs request default timeout time? Doing HTTP requests FROM Laravel to an external API CORS jQuery AJAX request Node.js request CERT_HAS_EXPIRED What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Examples related to httpclient

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M? PHP GuzzleHttp. How to make a post request with params? C#: HttpClient with POST parameters How to send a Post body in the HttpClient request in Windows Phone 8? The type List is not generic; it cannot be parameterized with arguments [HTTPClient] How to add,set and get Header in request of HttpClient? No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain' SSL "Peer Not Authenticated" error with HttpClient 4.1 Apache HttpClient Interim Error: NoHttpResponseException Common HTTPclient and proxy

Examples related to guzzle

Guzzlehttp - How get the body of a response from Guzzle 6? Guzzle 6: no more json() method for responses PHP GuzzleHttp. How to make a post request with params? How can I use Guzzle to send a POST request in JSON? Handle Guzzle exception and get HTTP body Catching exceptions from Guzzle