Laravel 8 PHP Guzzle Http Client GET and POST Examples

  2764 views   6 months ago Laravel

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','[email protected]');
Route::post('post_request','[email protected]');

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
}

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]