Monitor HTTP Interactions with Laravel's New Http::record() Method

Laravel's HTTP client just got more testable with the Http::record() method, allowing you to monitor real HTTP requests while maintaining actual communication with external services.
When building and testing applications that communicate with external APIs, it's often valuable to inspect the details of HTTP interactions. Laravel's HTTP client already allowed faking responses for testing, but sometimes you need to make real requests while still analyzing what's happening under the hood.
Let's see how the new Http::record() method works:
use Illuminate\Support\Facades\Http;
// Start recording HTTP interactions
Http::record();
// Make actual HTTP requests
Http::get('https://example.com/api/users');
Http::post('https://example.com/api/orders', ['product_id' => 123]);
// Access the recorded requests and responses
Http::recorded(function ($request, $response) {
// Analyze request/response details
});
Real-World Example
The Http::record() method is particularly useful for debugging, logging, or testing scenarios where you need to maintain real communication with external services. Here's a practical example:
public function testProductApiIntegration()
{
// Start recording HTTP interactions
Http::record();
// Perform the actual operation that makes API calls
$result = $this->app->make(ProductService::class)->syncWithExternalApi();
// Verify the operation was successful
$this->assertTrue($result);
// Now verify the HTTP interactions
$apiCallCount = 0;
$allStatusCodesSuccessful = true;
Http::recorded(function ($request, $response) use (&$apiCallCount, &$allStatusCodesSuccessful) {
$apiCallCount++;
// Check response status
if ($response->status() >= 400) {
$allStatusCodesSuccessful = false;
}
// Log the interaction for debugging
Log::debug('API Call', [
'url' => $request->url(),
'method' => $request->method(),
'status' => $response->status()
]);
});
$this->assertGreaterThan(0, $apiCallCount, 'No API calls were made');
$this->assertTrue($allStatusCodesSuccessful, 'Some API calls failed');
}
The key benefit of Http::record() is that it allows inspection without modification. Unlike Http::fake(), which prevents real HTTP requests from occurring, Http::record() simply monitors the interactions while allowing them to proceed normally.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter (https://x.com/harrisrafto), Bluesky (https://bsky.app/profile/harrisrafto.eu), and YouTube (https://www.youtube.com/@harrisrafto). It helps a lot!