Table Of Contents
Problem
You need to authenticate API requests to external services using Bearer tokens with Laravel's HTTP client.
Solution
Use the withToken()
method or withHeaders()
to send Bearer tokens:
use Illuminate\Support\Facades\Http;
// Method 1: Using withToken() (recommended)
$response = Http::withToken('your-api-token')
->get('https://api.example.com/users');
// Method 2: Using withHeaders()
$response = Http::withHeaders([
'Authorization' => 'Bearer your-api-token',
'Accept' => 'application/json',
])->get('https://api.example.com/users');
// Method 3: Using acceptJson() with token
$response = Http::acceptJson()
->withToken('your-api-token')
->post('https://api.example.com/users', [
'name' => 'John Doe',
'email' => 'john@example.com'
]);
Real-world example with error handling:
class ExternalApiService
{
private string $token;
private string $baseUrl;
public function __construct()
{
$this->token = config('services.external_api.token');
$this->baseUrl = config('services.external_api.url');
}
public function getUsers()
{
$response = Http::timeout(30)
->withToken($this->token)
->get("{$this->baseUrl}/users");
if ($response->failed()) {
throw new \Exception("API request failed: " . $response->body());
}
return $response->json();
}
public function createUser(array $userData)
{
return Http::withToken($this->token)
->post("{$this->baseUrl}/users", $userData)
->throw()
->json();
}
}
Why It Works
The withToken()
method automatically adds the Authorization: Bearer {token}
header to your request. This is the standard format for Bearer token authentication that most APIs expect. Laravel's HTTP client handles the formatting automatically.
Advanced usage with dynamic tokens:
// Using different tokens per request
$userToken = auth()->user()->api_token;
$adminToken = config('services.admin_api.token');
$userResponse = Http::withToken($userToken)
->get('https://api.example.com/user/profile');
$adminResponse = Http::withToken($adminToken)
->get('https://api.example.com/admin/users');
// Chaining multiple headers
$response = Http::withToken($token)
->withHeaders([
'X-API-Version' => '1.0',
'X-Client-ID' => 'laravel-app',
])
->retry(3, 100)
->get('https://api.example.com/data');
Related: Laravel Collections: Beyond Basic Array Operations | Laravel Events and Listeners: Building Decoupled Applications | Building Multi-tenant Applications with Laravel: A Comprehensive Guide | Laravel Sanctum: API Token Authentication Made Simple | API Authentication & Security 2025: Complete Guide
Add Comment
No comments yet. Be the first to comment!