Consuming rest api in laravel using guzzle

#1

i am implementing a web based calculator that consumes a rest api and am using guzzle. the webservice only accepts get requests. I would like to get the data from a html form and send it to the webservice to calculate and return me the result based on the arithmetic operation selected. am using laravel. my code is as below

  public function getRemoteData(Request $request)
    {
        $data = $request->all();

        $operation = $data['operation'];
        $num1 = $data['num1'];
        $num2 = $data['num2'];
        $client = new Client();

       $request = $client->get("http://127.0.0.1:3000/multiply/4/3");
        $response = $request->getBody()->getContents();
        
        return $response;

    }

my route
Route::get(’/data’, ‘calculator@getRemoteData’);

my html form

<form action="/data" method="get">
        <div class="form-row">
          <div class="form-group col-md-6">
            <input type="number"  name="num1" class="form-control" id="num1" placeholder="first number">
          </div>
          <div class="form-group col-md-6">
            <input type="number" name="num2" class="form-control" id="num2" placeholder="Second number">
          </div>
        </div>
        <div class="form-row">
          <div class="form-group col-md-6">
            <input type="number" name="result" class="form-control" id="result" placeholder="Result will be here" readonly>
          </div>
          <div class="form-group col-md-6">
            <select id="inputState" name="operation" class="form-control">
              <option selected>Choose an operation to perform</option>
              <option>add</option>
              <option>subtract</option>
              <option>multiply</option>
              <option>divide</option>
            </select>
          </div>
        </div>
        <button type="submit" class="btn btn-primary">Calculate</button>
        <button type="submit" class="btn btn-info">Clear</button>
      </form>
0 Likes

#2

So you posted your concept to us. What now?

0 Likes

#3

No. I need help on how to pass on form data to the api. it only accepts get request

0 Likes

#4

Instead of using $client->get(), you should use the $client-post() method and specify the form fields as an array in the form_params request option. So something like this should work:

$request = $client->post('http://127.0.0.1:3000/data', [
    'form_params' => [
        'num1' => $num1,
        'num2' => $num2,
    ]
]);
0 Likes

#5

You receive the data via $_POST or any middleware you use, maybe $request and can then give this data to Guzzle, as the documentation states:

http://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters

0 Likes

#6

Please ignore myself previous post. I misread your question.

0 Likes