Laravel
Intermediate
Blade & HTTP
· 6 min read
The Laravel HTTP Client
Lesson 20 of 33 in the Laravel learning path.
How do I call another JSON API from a Laravel action?
Http::timeout()->get() calls another service and returns a response object.
A catalog import should fail visibly on a 500 and should not hang the request forever.
Syntax & Parameters
Http::timeout(5)->acceptJson()->get($url)->throw()->json();
Example
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class CatalogClient
{
public function lesson(string $url): array
{
$response = Http::timeout(5)
->acceptJson()
->get($url);
$response->throw();
$data = $response->json();
return [
'title' => (string) ($data['title'] ?? ''),
'track' => (string) ($data['track'] ?? ''),
];
}
}
Expected Output
A successful call returns an array with title and track. A 404 throws a request exception.
Line-by-Line Walkthrough
- timeout 5 stops a hung host.
- acceptJson sets the Accept header.
- get sends the request.
- throw raises on a 4xx or 5xx.
- json decodes the body as an array.
- Only title and track are returned.
- Missing keys become empty strings.
- The caller still validates before insert.
Common Pitfalls & Security
Watch the failure mode, not only the happy path.
- No timeout means a stuck upstream holds a PHP worker.
- throw() is what turns a 500 into an exception. Skipping it looks like success.
- Returning the whole JSON leaks fields you did not review.
- SSRF: do not pass a user-supplied URL straight to get. Allow-list the host.
Best Practices & Modern Standards
Set a timeout, accept JSON, and throw on failure.
Map the payload down to the fields you store. Allow-list remote hosts.
Real-World Use
An import button pulls a partner catalog lesson and stores only the title and track after validation.
Frequently Asked Questions
What does throw do?
It raises if the status is not successful, so you do not decode an error page as JSON.
How do I send a bearer token?
Http::withToken($token) before get.
Can I fake it in tests?
Yes. Http::fake() returns a canned response and asserts the URL.
Should the user choose any URL?
No. That is a server-side request forgery risk. Allow-list the host.