Kritim Yantra
May 16, 2025
In modern web development, interacting with external APIs is a common necessity. Whether you're fetching data from a third-party service, sending HTTP requests, or handling webhooks, Laravel makes it seamless with Guzzle HTTP Client.
In this tutorial, we'll explore how to use Guzzle HTTP Client in Laravel 12 to send GET, POST, PUT, and DELETE requests. By the end, you'll be able to integrate external APIs effortlessly into your Laravel applications.
Guzzle is a powerful PHP HTTP client that simplifies sending HTTP requests and integrating with web services. Laravel includes Guzzle by default, so you don’t need to install it separately.
Before proceeding, ensure you have:
First, let’s create a controller to handle HTTP requests.
php artisan make:controller ApiController
Now, open app/Http/Controllers/ApiController.php
and add the following methods.
Fetching data from an API is simple with Guzzle.
use Illuminate\Support\Facades\Http;
public function getPosts()
{
$response = Http::get('https://jsonplaceholder.typicode.com/posts');
if ($response->successful()) {
$posts = $response->json();
return response()->json($posts);
} else {
return response()->json(['error' => 'Failed to fetch data'], 500);
}
}
Http::get()
sends a GET request.$response->successful()
checks if the request was successful (status code 200-299).$response->json()
parses the JSON response.To send data to an API, use a POST request.
public function createPost()
{
$data = [
'title' => 'New Post',
'body' => 'This is a test post.',
'userId' => 1,
];
$response = Http::post('https://jsonplaceholder.typicode.com/posts', $data);
if ($response->successful()) {
return response()->json($response->json(), 201);
} else {
return response()->json(['error' => 'Failed to create post'], 500);
}
}
Http::post()
sends a POST request with the given data.201 Created
status on success.To update an existing resource, use a PUT request.
public function updatePost($id)
{
$data = [
'title' => 'Updated Post',
'body' => 'This post has been updated.',
];
$response = Http::put("https://jsonplaceholder.typicode.com/posts/{$id}", $data);
if ($response->successful()) {
return response()->json($response->json());
} else {
return response()->json(['error' => 'Failed to update post'], 500);
}
}
Http::put()
updates the resource at the given endpoint.$id
parameter specifies which post to update.To delete a resource, use a DELETE request.
public function deletePost($id)
{
$response = Http::delete("https://jsonplaceholder.typicode.com/posts/{$id}");
if ($response->successful()) {
return response()->json(['message' => 'Post deleted successfully']);
} else {
return response()->json(['error' => 'Failed to delete post'], 500);
}
}
Http::delete()
removes the specified resource.Many APIs require authentication headers. Here’s how to add them:
public function getProtectedData()
{
$response = Http::withHeaders([
'Authorization' => 'Bearer YOUR_ACCESS_TOKEN',
'Accept' => 'application/json',
])->get('https://api.example.com/protected-data');
return $response->json();
}
withHeaders()
allows adding custom headers.Guzzle allows setting timeouts and handling errors gracefully.
public function fetchWithTimeout()
{
try {
$response = Http::timeout(10) // 10 seconds timeout
->get('https://jsonplaceholder.typicode.com/posts');
return $response->json();
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
timeout(10)
sets a max request duration.try-catch
block handles potential exceptions.Guzzle HTTP Client in Laravel 12 makes API interactions effortless. Whether you're fetching, creating, updating, or deleting data, Guzzle provides a clean and powerful way to handle HTTP requests.
✅ Use Http::get()
, post()
, put()
, delete()
for different HTTP methods.
✅ Add headers with withHeaders()
.
✅ Handle errors and timeouts gracefully.
✅ Always check $response->successful()
before processing results.
Now, you're ready to integrate any API into your Laravel application! 🚀
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google