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

Syntax
Http::timeout(5)->acceptJson()->get($url)->throw()->json();

Example

app/Services/CatalogClient.php
<?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

  1. timeout 5 stops a hung host.
  2. acceptJson sets the Accept header.
  3. get sends the request.
  4. throw raises on a 4xx or 5xx.
  5. json decodes the body as an array.
  6. Only title and track are returned.
  7. Missing keys become empty strings.
  8. 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…