Laravel Guzzle Http Client POST Request Example

By Hardik Savani November 5, 2023 Category : Laravel JSON

A very few days ago i was working on my laravel 5.3 application and i require to use WordPress API. I was thinking how to use WP API, But i found docs for WordPress API, But i don't know how to fire GET, POST, PUT and DELETE request from Laravel side. I did search lot but nothing to find good.

However, I found guzzlehttp package for laravel and little bit read about that, i understand we can simply fire get, post, delete etc request from laravel using guzzlehttp client through. But i was also one query how to make basic auto with POST request but here also solution for this.

So in this post, we learn how to make post request from laravel using http guzzle client. In this example i also added basic authentication for example. It is pretty simple, after this example you can simply use other Website APIs too.

So, For GuzzleHttp, we require "guzzlehttp/guzzle" composer package on our laravel application, Let's install this package by using following command:

Install guzzlehttp/guzzle package

composer require guzzlehttp/guzzle:~5.0

Ok, now we are ready to use "GuzzleHttp\Client" Class on Laravel application, So in route file we can make simple POST request like this way, It is for your understanding, you can call your api instead of "http://wp.dev/index.php/wp-json/wp/v2/posts", Let's see:

Add In Your Route File

Route::get('guzzle-http-post-request', function()

{

$body['title'] = "Body Title";

$body['content'] = "Body Description";


$client = new \GuzzleHttp\Client();

$url = "http://wp.dev/index.php/wp-json/wp/v2/posts";


$response = $client->createRequest("POST", $url, ['auth' => ['root','root'],'body'=>$body]);


$response = $client->send($response);


dd($response);

});

You simple run GET, PUT and DELETE request like this way.

I hope it can help you...

Shares