Guzzle Http Request With Authorization Token

Photo by Markus Spiske on Unsplash

單純紀錄自己用的 Guzzle Request 模板

簡單版

use GuzzleHttp\Client;$client = new GuzzleHttp\Client(['base_uri' => 'https://api.example/']);$token = '<TOKEN>';
$method = 'GET';
$url = 'v1.3/products';
$headers = ['Authorization' => 'Bearer ' . $token];//$headers must be an array
$response = $client->request($method, $url, [
'headers' => $headers
]);
dd(json_decode($response->getBody(),true));

try & catch 版

use GuzzleHttp\Client as Client;
use GuzzleHttp\Psr7\Request as Request;
use GuzzleHttp\Exception\ClientException as ClientException;
$client = new Client(['base_uri' => 'https://api.example/']);$token = '<TOKEN>'
$method = 'POST';
$url = 'URL'
$header = ['Authorization'=>'Bearer '.$token, 'Content-Type'=>'application/json'];
$body = 'BODY';
$request = new Request($method, $url, $header, $body);try{
$response = $client->send($request);
dd(json_decode($response->getBody(),true));
} catch (ClientException $e){
dd(json_decode($e->getResponse()->getBody(),true));
}

--

--

--

不專業的技術筆記,偶爾聊聊動畫

Recommended from Medium

How do computers read code?

Introducing Jovo Framework v2

Important Functions to deploy code on AWS SageMaker

What is story points estimation in Agile: benefits of relative evaluation

Outdated belief #8: A/B testing is only for online systems

Solr Automation

Loops and statements in Python: A deep understanding (with examples)

loops in Python: a snake…

Principal Project Associate, Project Associate, & Other — 16 Posts

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lightfish Uhuhu

Lightfish Uhuhu

大學設計系,當了三年 3D 動畫師,現為後端工程師

More from Medium

Creating your own Oauth2 server using Laravel Passport —Implicit grant flow

Configuring Laravel 7 For Use With PhpRedis using Homestead

How to add a custom virtual host on Windows 11

Fix Gitlab SSH issues with Laravel Deploy