To make request from the application we can use guzzle http package. It provides various options to manage all the things regarding reuest and response.

In this turorial we wil se how we can make http reuest and get response in laravel 8.

Step - 1 : Create new laravel application

composer create-project --prefer-dist laravel/laravel guzzle_request

Step - 2 : install guzzle http package

composer require guzzlehttp/guzzle

Step - 3 : setup routes

Add this routes in web.php

Route::get('get_request','GuzzleExampleController@index');
Route::post('post_request','GuzzleExampleController@store');

Step - 4 : setup controller

app/Http/Controllers/GuzzleExampleController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class GuzzleExampleController extends Controller
{
    public function index()
    {
        $response = Http::get('https://jsonplaceholder.typicode.com/todos');
  
        $jsonData = $response->json();
        
        dd($jsonData);

        echo "<pre> status:";
        print_r($response->status());
        echo "<br/> ok:";
        print_r($response->ok());
        echo "<br/> successful:";
        print_r($response->successful());
        echo "<br/> serverError:";
        print_r($response->serverError());
        echo "<br/> clientError:";
        print_r($response->clientError());
        echo "<br/> headers:";
        print_r($response->headers());
    }

    public function store()
    {
        $response = Http::post('http://jsonplaceholder.typicode.com/posts', [
                    'title' => 'guzzle example title',
                    'body' => 'guzzle example body',
                ]);
  
        dd($response->successful());
    }
}

Step - 5 : Output for get request

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false
  },
  {
    "userId": 1,
    "id": 4,
    "title": "et porro tempora",
    "completed": true
  },
  ...
  ]

Step - 6 : Output for POST request

{
  	"id": 101
}

 


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments