Integrating third-party APIs into your Yii2 application allows you to extend functionality, fetch external data, and interact with services like payment gateways, social media APIs, or weather services.
In this guide, we’ll cover:
yii\httpclient, and Guzzle)There are multiple ways to make HTTP requests in Yii2:
Yii2 does not include an HTTP client by default, but PHP cURL is a built-in option.
function fetchApiData($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
$data = fetchApiData('https://jsonplaceholder.typicode.com/posts');
print_r($data);yii\httpclient)Yii2 provides an HTTP client extension for easier API calls.
composer require yiisoft/yii2-httpclientuse yii\httpclient\Client;
$client = new Client();
$response = $client->createRequest()
->setMethod('GET')
->setUrl('https://jsonplaceholder.typicode.com/posts')
->send();
if ($response->isOk) {
print_r($response->data);
}Guzzle is a powerful PHP HTTP client with asynchronous requests, middleware support, and advanced authentication.
composer require guzzlehttp/guzzleuse GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts');
$data = json_decode($response->getBody(), true);
print_r($data);Many APIs require authentication methods like API keys, OAuth, or JWT.
Some APIs require an API key in the header or query parameters.
$response = $client->createRequest()
->setMethod('GET')
->setUrl('https://api.example.com/data')
->addHeaders(['Authorization' => 'Bearer YOUR_API_KEY'])
->send();$response = $client->createRequest()
->setMethod('GET')
->setUrl('https://api.example.com/data?api_key=YOUR_API_KEY')
->send();For APIs like Google, Facebook, and Twitter, OAuth 2.0 is required.
composer require league/oauth2-clientuse League\OAuth2\Client\Provider\GenericProvider;
$provider = new GenericProvider([
'clientId' => 'your-client-id',
'clientSecret' => 'your-client-secret',
'redirectUri' => 'http://your-app.com/callback',
'urlAuthorize' => 'https://api.example.com/oauth/authorize',
'urlAccessToken' => 'https://api.example.com/oauth/token',
'urlResourceOwnerDetails' => 'https://api.example.com/me',
]);
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
echo "Access Token: " . $accessToken->getToken();Now, use this token in API calls:
$response = $client->createRequest()
->setMethod('GET')
->setUrl('https://api.example.com/data')
->addHeaders(['Authorization' => 'Bearer ' . $accessToken->getToken()])
->send();For APIs requiring JWT authentication, first obtain a JWT token:
$response = $client->createRequest()
->setMethod('POST')
->setUrl('https://api.example.com/login')
->setData(['username' => 'user', 'password' => 'pass'])
->send();
$token = $response->data['token'];Use this token in further requests:
$response = $client->createRequest()
->setMethod('GET')
->setUrl('https://api.example.com/protected-data')
->addHeaders(['Authorization' => 'Bearer ' . $token])
->send();APIs return data in JSON or XML, which must be processed correctly.
Most APIs return JSON data. Convert it to an array:
$data = json_decode($response->getBody(), true);
print_r($data);If the API returns XML, convert it using SimpleXMLElement:
$xml = simplexml_load_string($response->getBody());
$json = json_encode($xml);
$data = json_decode($json, true);
print_r($data);Always handle timeouts, errors, and API failures.
try {
$response = $client->request('GET', 'https://api.example.com/data');
if ($response->getStatusCode() !== 200) {
throw new \Exception("API returned an error: " . $response->getBody());
}
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}Set timeouts to prevent long delays:
$client = new Client([
'timeout' => 5.0, // Timeout after 5 seconds
]);For unreliable APIs, use Guzzle retries:
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
$stack = HandlerStack::create();
$stack->push(Middleware::retry(function ($retries, $request, $response, $exception) {
return $retries < 3 && ($exception || $response->getStatusCode() >= 500);
}));
$client = new Client(['handler' => $stack]);Yii2 provides multiple ways to consume third-party APIs, from cURL to Guzzle. Using proper authentication, error handling, and caching, you can integrate external APIs securely and efficiently.
Sign in to join the discussion and post comments.
Sign in