In the Laravel, you can create RESTful and SOAP API. These APIs can be integrated into the client-side application to get the data in the JSON or XML format. So, this can be very helpful when you want to keep your application to more secure and robust by separating the front-end and back-end. This makes the web and mobile application much faster than combining both front-end and back-end into a single application. Generally, it makes the web application very light-weight. The application runs very smoothly just because of the JSON data. So, today, in this post, I will gonna show you the API request handling in Laravel. That is called Laravel Http Client That means we can call the third party APIs or even the same Laravel RESTful APIs using the Laravel Guzzle library.
Prerequisites
We are going to create a Laravel 7 project. So, as the configuration of PHP and MySQL your system must be ready with the specified version.
- PHP >= 7.2.5
- MySQL > 5
- Apache/Nginx Server
- Composer
Here, we will be creating the Laravel 7 project using the composer. So, let’s start by creating a new project.
But before creating the project, let’s know about the JSON and the Http request.
JSON interchanges the data and makes it a very light-weight format. Which can be easily implemented in the latest technologies such as Angular, React, Vue, etc.
Create Project in Laravel 7 For Guzzle Http Request
Windows user open the command prompt and MAC and Linux user open the terminal and create a new project.
composer create-project --prefer-dist laravel/laravel laravel-guzzle-http
Here, the new project has been creation has been started. So, just wait till it finishes.
How to Implement Yajra DataTable in Laravel 7
Install Laravel Guzzle Http Library
Now, we will install the Laravel Guzzle Http library inside our application. This will allow us to manage the Http requests. So, let’s install the package.
If you don’t know the exact package name then you can search the package like this.
composer require
Now, enter the package related keyword like guzzle. The list of available package will be showing you in the result.
Here, the list of packages are available with the entered keyword. Now, choose the package to install.
Here, we will install the Guzzle HTTP library.
composer require guzzlehttp/guzzle
The package will take a couple of minutes to add inside the project.
You can check the added library inside the composer.json file. In the root of the project directory, you will find the composer.json file.
How to Send Email Using Gmail SMTP in Laravel 7
In Laravel, the composer.json file contains the libraries and packages that are installed. Here, we have created the Laravel 7 project. So, the current version contains the Laravel Guzzle Http version 6.3. This is the inbuilt library that we will be using in this post.
Create a Controller in Laravel
I will be creating one controller to demonstrate the Laravel Guzzle Http request. So, let’s create it.
php artisan make:controller ApiHandlerController
After creating the controller, let’s create the functionality for the different request type. Such as GET, POST, PUT, PATCH, and DELETE. So, open the controller and add a namespace for the Guzzle Http client.
use Illuminate\Support\Facades\Http;
Now, we will create a function and inside the function, we will be implementing a GET request. I will use a demo API for the blog post. You can also visit the JSONPlaceholder for the different demo API.
Guzzle Http GET Request
So, firstly, we will start with the GET request. In Get request, I will be extracting the data from the API response.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class ApiHandlerController extends Controller
{
// --------------- [ Get request ] -----------------------
public function getPosts() {
$response = Http::get("https://jsonplaceholder.typicode.com/posts");
dd($response);
}
}
In the above controller function, I have used the GET request. Inside the Http::get() method, I have passed the API endpoint that I am using for the demo.
Now, create a route for the function. You can create web or api route for this. This will depend upon your usage.
Route::get("posts", "ApiHandlerController@getPosts");
I have added the route inside the web.php. Now, run the project with the above endpoint to see the result.
How to Implement Google Charts in Laravel 7
As a result, you can see we have got the API response. But, it is very difficult to find out the exact data from the above response. So, let’s make it more clear. You can use the print_r() function for displaying the result.
// --------------- [ Get request ] -----------------------
public function getPosts() {
$response = Http::get("https://jsonplaceholder.typicode.com/posts");
dd($response->json());
}
I have converted the response in array by using the json() function.
Laravel 7 Yajra DataTable with Server Side Processing
Guzzle Http Request Response to JSON
You can convert the same response to JSON or if you want then you can return the data into the view. Here, I am not going to create a view for this. I am just showing the API response only.
Let’s convert it into the JSON.
public function getPosts() {
$response = Http::get("https://jsonplaceholder.typicode.com/posts");
$response = $response->json();
return response()->json(["status" => "success", "count" => count($response), "data" => $response]);
}
To see the JSON response, use a JSON parser or you can use Postman for the API response.
Laravel 7 RESTful APIs with Passport Authentication
Guzzle Http POST Request
We can use POST request to submit the data using the RESTful API. You can pass the data using the form or by the postman. So for passing the data into the API, we will be creating an array of data. Here, is the function for passing the data into the API.
public function createPost() {
$response = Http::post("https://jsonplaceholder.typicode.com/posts",
[
"userId" => 2,
"title" => "Laravel http client example",
"body" => "This is a post on Laravel Guzzle http client"
]
);
$response = $response->body();
print_r($response);
}
In the above function, I have passed the data static as the API required. You can pass it dynamically by reading the data using the Request object.
Similarly, for the above function, create an endpoint (route).
Route::post("create-post", "ApiHandlerController@createPost");
After hitting the above endpoint, you will get the response as the data. Here, the post has been created successfully.
Laravel 7 Upload Multiple Images with Image Validation
Guzzle Http PUT Request
For updating the data, we can use PUT request. This type of request takes the primary field as an parameter and in the body the content will be passed.
public function updatePost() {
$response = Http::post("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->body();
print_r($response);
}
Guzzle Http DELETE Request
For deleting the data using the RESTful API, we use DELETE request.
public function deletePost() {
$response = Http::delete("https://jsonplaceholder.typicode.com/posts/1");
$response = $response->body();
print_r($response);
}
So, after including all the functions in the controller, the final code will be –
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class ApiHandlerController extends Controller
{
// --------------- [ Get request ] -----------------------
public function getPosts() {
$response = Http::get("https://jsonplaceholder.typicode.com/posts");
$response = $response->json();
return response()->json(["status" => "success", "count" => count($response), "data" => $response]);
}
// --------------- [ Create Post ] -----------------------
public function createPost() {
$response = Http::post("https://jsonplaceholder.typicode.com/posts",
[
"userId" => 1,
"title" => "Laravel http client example",
"body" => "This is a post on Laravel Guzzle http client"
]
);
$response = $response->body();
print_r($response);
}
// -------------- [ 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->body();
print_r($response);
}
// -------------- [ Delete Post ] -----------------------
public function deletePost() {
$response = Http::delete("https://jsonplaceholder.typicode.com/posts/1");
$response = $response->body();
print_r($response);
}
}
Also, for the above functions, here are the routes.
Route
Here, these will be the routes for the above functions. These routes would be added in the routes/web.php file.
Route::get("posts", "ApiHandlerController@getPosts");
Route::post("create-post", "ApiHandlerController@createPost");
Route::put("update-post", "ApiHandlerController@updatePost");
Route::delete("delete-post", "ApiHandlerController@deletePost");
Conclusion
So, finally we have completed the Laravel Guzzle http client for the RESTful APIs handling. This demo will guide you in the HTTP request handling withe any third party APIs. HTTP Client in Laravel, overcomes the use of cURL request. Hope, it will be very helpful for you. If you find any difficulty regarding this post, then please let me know in the comment section.
Leave a Reply