There are lots of library and packages are available for handling the API requests on the client-side. But what about the server-side? If we talk about the core PHP then you can handle the API requests using the cURL. But, do you think is it a good practice to use cURL in a PHP framework like Laravel? No, because, Laravel 8 provides an inbuilt package that is called Guzzle Http. This feature was added in Laravel 7. But in the previous version, you had to install it manually. The Guzzle Http supports the request types such as GET, POST, PUT, PATCH, and DELETE. Therefore, the client request handling can be done easily in Laravel 8. In this post, I will show you the implementation of the Laravel Guzzle Http for request handling. So, let’s start with a new project.
Prerequisites
We will create a new project in Laravel 8. So, it required the following tools with the specified version.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
When you are ready, create a new project.
Create New Project For Laravel 8 Guzzle Http
For creating the new project in Laravel 8, I will use the composer. So, open the terminal and create a new project.
composer create-project --prefer-dist laravel/laravel guzzle
Here, the Laravel 8 installation has started.
After finishing the project setup, let’s check the Guzzle Http package.
How to Implement Yajra DataTables in Laravel 8
You can find the package inside the composer.json file. Here, you can see there is a default library of the Guzzle Http.
In the next step, we will create a controller. Then in that controller, we will handle the HTTP request.
How to Send Emails Using Twilio Sendgrid in Laravel 8
Create a Controller For Guzzle Http Request Handling
For implementing the functionality of request handling, we’ll require a controller. So, open the terminal and create a controller with any name.
php artisan make:controller RequestController
Here, I have created the controller.
Firstly, you will have to import the namespace for this package.
use Illuminate\Support\Facades\Http;
Laravel 8 Guzzle Http GET Request
For the testing purpose, I am using the free and open-source REST API. This generates the fake data, you can find out in JSONPlaceholder.
For the GET request handling, I have written the below snippet.
// GET Request for POST listing
public function postsListing() {
$response = Http::get("https://jsonplaceholder.typicode.com/posts");
dd($response);
}
For the above function, you will have to add a route. You can create a web or API route for this. I am creating the API route because I will pass the form data for the POST request. Otherwise, we will have to pass the endpoint to accept the data without CSRF protection. So, no need to do this, simply create the Route in the api.php file.
<?php
use Illuminate\Http\Request;
use App\Http\Controllers\RequestController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
// Guzzle Http GET Request
Route::get("posts", [RequestController::class, "postsListing"]);
After adding the GET route, run the application.
In the result, I got the following response as showing below. Here, I have used die and dump to check only the API response.
So, it is working perfectly, we are getting the API response. But this is not the exact output, that we are expecting. So, we will have to make it more clear for getting the data.
So, let’s convert the response to array.
// GET Request for POST listing
public function postsListing() {
$response = Http::get("https://jsonplaceholder.typicode.com/posts");
$response = $response->json();
dd($response);
}
Now, re-run the application to see the response data into array.
similarly, we can convert this response to JSON.
// GET Request for POST listing
public function postsListing() {
$response = Http::get("https://jsonplaceholder.typicode.com/posts");
$response = $response->json();
return response()->json(["status" => 200, "count"=> count($response), "data"=> $response]);
}
To beautify the JSON result, you can use any JSON parser or Postman. Here, I have hit the URL in the postman. Then data is showing in the JSON.
So, this was for the GET request response. Now, we can post the data to the API using the Laravel 8 Guzzle Http.
Create Auth Using Jetstream and Intertia js in Laravel 8
Guzzle Http POST Request
We can pass data to the REST API through form fields. You can use the Postman or any form to create dynamic data. Here, you will have to pass the data in the form of the array. You can pass static as well as dynamic data. So, firstly, I will pass the static data and will show you the result.
// POST Request to create a new Post
public function createPost(Request $request) {
$response = Http::post("https://jsonplaceholder.typicode.com/posts",
[
"userId" => 1,
"title" => "Laravel 8 http client example",
"body" => "This is a post on Laravel 8 Guzzle http request handling"
]
);
$response = $response->body();
print_r($response);
}
I have passed the data static. Now, define a route for this function.
// Guzzle Http POST Request
Route::post("create-post", [RequestController::class, "createPost"]);
Now, hit the endpoint and check the result.
Here, the post is created successfully. But, if you want to submit the data dynamically then you can accept the value from the form-data. Then you will have to create an array of the data. So, let’s do it by accepting the data dynamically.
// POST Request to create a new Post
public function createPost(Request $request) {
$dataArray = array(
"userId" => $request->userId,
"title" => $request->title,
"body" => $request->body
);
$response = Http::post("https://jsonplaceholder.typicode.com/posts", $dataArray);
$response = $response->body();
print_r($response);
}
For using the POST request and passing the dynamic data, I used the Postman. Because, I didn’t create any form for passing these inputs. So, for the testing purpose, I passed data from the body->form-data and chosen the request type to POST.
After hitting the API, I go the result as showing below. Here, the post has been created and returned the created post.
So, the Guzzle Http POST request has completed.
How to Create Auth with Jetstream and Livewire in Laravel 8
PUT Request in Guzzle Http
You can use PUT or PATCH request to update the records. Here, I have used the PUT request to this API. Then on the basis of the post id, the post will gonna update. So, I have passed the data in the form of an array inside the API.
// PUT Request to update Post
public function updatePost() {
$response = Http::put("https://jsonplaceholder.typicode.com/posts/1",
[
"userId" => 1,
"title" => "Laravel http client example using Guzzle http",
"body" => "This is a post on Laravel Guzzle http client"
]
);
$response = $response->json();
return response()->json(["status" => 200, "data"=> $response]);
}
Similarly, add the route as the PUT method.
// Guzzle Http PUT Request to update post
Route::put("update-post", [RequestController::class, "updatePost"]);
You will have the result as the updated post.
At last, we will use the delete request for deleting the post.
Laravel 8 Multiple Images Upload with Validation
Guzzle Http Delete Request
Similarly, you can use DELETE request for deleting the record. Here, is the basic snippet to use the delete request in Guzzle Http.
// DELETE Request to delete a post
public function deletePost() {
$response = Http::delete("https://jsonplaceholder.typicode.com/posts/1");
$response = $response->body();
print_r($response);
}
Conclusion
We have use Laravel 8 Guzzle Http package for handling the APIs requests. This makes easy to handle any kind of APIs request in PHP without using the cURL. It is more faster than the cURL requests. So, we implemented the request types such as GET, POST, PUT and DELETE. I used over a fake API for the testing purpose. You can use it by creating any API. So, I wish, this can be helpful for you all. Thank you.
Leave a Reply