Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send parameters for a PUT request in Guzzle 5?

Tags:

rest

php

guzzle

I have this code for sending parameters for a POST request, which works:

$client = new GuzzleHttp\Client();
$request = $client->createRequest('POST', 'http://example.com/test.php');
$body = $request->getBody();

$request->getBody()->replaceFields([
    'name' => 'Bob'
]);

However, when I change POST to PUT, I get this error:

Call to a member function replaceFields() on a non-object

This is because getBody is returning null.

Is it actually correct to send PUT parameters in the body? Or should I do it in the URL?

like image 483
Gnuffo1 Avatar asked Jan 26 '15 15:01

Gnuffo1


People also ask

How do I send parameters in guzzle?

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. Save this answer.

How do I send a POST request with guzzle?

Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);

How do I send raw data from guzzle?

Guzzle provides several methods of uploading data. You can send requests that contain a stream of data by passing a string, resource returned from fopen , or a GuzzleHttp\Stream\StreamInterface object to the body request option. $r = $client->post('http://httpbin.org/post', ['body' => 'raw data']);

How do you send a header on guzzle?

// Set various headers on a request $client->request('GET', '/get', [ 'headers' => [ 'User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'] ] ]); Headers may be added as default options when creating a client.


2 Answers

According to the manual,

The body option is used to control the body of an entity enclosing request (e.g., PUT, POST, PATCH).

The documented method of put'ing is:

$client = new GuzzleHttp\Client();

$client->put('http://httpbin.org', [
    'headers'         => ['X-Foo' => 'Bar'],
    'body'            => [
        'field' => 'abc',
        'other_field' => '123'
    ],
    'allow_redirects' => false,
    'timeout'         => 5
]);

Edit

Based on your comment:

You are missing the third parameter of the createRequest function - an array of key/value pairs making up the post or put data:

$request = $client->createRequest('PUT', '/put', ['body' => ['foo' => 'bar']]);
like image 105
Richard Parnaby-King Avatar answered Oct 09 '22 15:10

Richard Parnaby-King


when service ise waiting json raw data

$request = $client->createRequest('PUT', '/yourpath', ['json' => ['key' => 'value']]);

or

$request = $client->createRequest('PUT', '/yourpath', ['body' => ['value']]);
like image 25
Ali Özyıldırım Avatar answered Oct 09 '22 16:10

Ali Özyıldırım