Farshad
Farshad

Reputation: 2000

How to send variable with the guzzle post method

I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:

$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);

so every thing is fine and static data is being send but I want to know how can I send a variable.

Upvotes: 2

Views: 8811

Answers (3)

Serhii Andriichuk
Serhii Andriichuk

Reputation: 998

You can try to use Guzzle json option:

$amount = $request->get('amount');

$client = new \GuzzleHttp\Client();

$response = $client->post(
    'http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', 
    [
        GuzzleHttp\RequestOptions::JSON => [
            'Amount' => $amount,
            'something' => '1',
            'Description' => 'desc',
        ]
    ]
);

Check Guzzle manual - http://docs.guzzlephp.org/en/stable/request-options.html#json

Upvotes: 0

Nishal K.R
Nishal K.R

Reputation: 1130

Amount can pass in an array and after you can encode with json using ```json_encode``

Hope this works for you.

$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$url   = "http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber";
$data   = [
            "amount"      => $amount,
            "something"   => "1",
            "description" => "desc",
          ];

$requestAPI = $client->post( $url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($data);
    ]);

Upvotes: 3

nitin7805
nitin7805

Reputation: 203

You can bind the data in form_params parameter like

$client = new \GuzzleHttp\Client();
$amount = $request->get('amount');
$requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
                   'form_params' => [
                        "Amount" => "i want to send $amount here",
                        "something" => "1",
                        "Description" => "desc",
                   ]
             ]);

Hope this works for you.

Upvotes: 4

Related Questions