Laravel 12 Guzzle HTTP Request Tutorial: A Complete Guide
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.
What is Guzzle?
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.
Prerequisites
Before proceeding, ensure you have:
- Laravel 12 installed
- Basic understanding of Laravel & HTTP methods (GET, POST, etc.)
- An API endpoint to test (we'll use JSONPlaceholder for demo)
Step 1: Setting Up a Laravel Controller
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.
Step 2: Making a GET Request
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);
}
}
Explanation:
Http::get()sends a GET request.$response->successful()checks if the request was successful (status code 200-299).$response->json()parses the JSON response.
Step 3: Making a POST Request
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);
}
}
Explanation:
Http::post()sends a POST request with the given data.- We return the API response with a
201 Createdstatus on success.
Step 4: Making a PUT Request
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);
}
}
Explanation:
Http::put()updates the resource at the given endpoint.- The
$idparameter specifies which post to update.
Step 5: Making a DELETE Request
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);
}
}
Explanation:
Http::delete()removes the specified resource.- Returns a success message if the deletion is successful.
Step 6: Handling Headers & Authentication
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();
}
Explanation:
withHeaders()allows adding custom headers.- Useful for API keys, Bearer tokens, etc.
Step 7: Error Handling & Timeouts
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);
}
}
Explanation:
timeout(10)sets a max request duration.- A
try-catchblock handles potential exceptions.
Conclusion
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.
Key Takeaways:
✅ 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! 🚀
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.