Consuming Third-Party APIs in Yii2

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:

  • Making HTTP Requests in Yii2 (cURL, yii\httpclient, and Guzzle)
  • Handling Authentication (API Keys, OAuth, and JWT)
  • Processing API Responses (JSON, XML)
  • Error Handling & Best Practices

1. Making HTTP Requests in Yii2

There are multiple ways to make HTTP requests in Yii2:

1.1 Using PHP cURL

Yii2 does not include an HTTP client by default, but PHP cURL is a built-in option.

Example: Fetching data from a REST API using cURL

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);
  • Pros: Available by default in PHP.
  • Cons: Requires manual setup for headers, authentication, and error handling.

1.2 Using Yii2 HTTP Client (yii\httpclient)

Yii2 provides an HTTP client extension for easier API calls.

Step 1: Install Yii2 HTTP Client

composer require yiisoft/yii2-httpclient

Step 2: Use it in Yii2

use 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);
}
  • Pros: Easy to use, supports JSON, XML, and headers.
  • Cons: Requires installation.

1.3 Using Guzzle (Recommended for Advanced Use)

Guzzle is a powerful PHP HTTP client with asynchronous requests, middleware support, and advanced authentication.

Step 1: Install Guzzle

composer require guzzlehttp/guzzle

Step 2: Use it in Yii2

use GuzzleHttp\Client;

$client = new Client();
$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts');

$data = json_decode($response->getBody(), true);
print_r($data);
  • Pros: Supports advanced features like retries, OAuth, and JSON handling.
  • Cons: Slightly heavier dependency.

2. Handling Authentication in API Calls

Many APIs require authentication methods like API keys, OAuth, or JWT.

2.1 API Key Authentication

Some APIs require an API key in the header or query parameters.

Example: Sending API Key in Header

$response = $client->createRequest()
    ->setMethod('GET')
    ->setUrl('https://api.example.com/data')
    ->addHeaders(['Authorization' => 'Bearer YOUR_API_KEY'])
    ->send();

Example: Sending API Key in URL

$response = $client->createRequest()
    ->setMethod('GET')
    ->setUrl('https://api.example.com/data?api_key=YOUR_API_KEY')
    ->send();

2.2 OAuth 2.0 Authentication

For APIs like Google, Facebook, and Twitter, OAuth 2.0 is required.

Step 1: Install OAuth Extension

composer require league/oauth2-client

Step 2: Implement OAuth Authentication

use 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();

2.3 JWT Authentication

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();

3. Handling API Responses

APIs return data in JSON or XML, which must be processed correctly.

3.1 Handling JSON Responses

Most APIs return JSON data. Convert it to an array:

$data = json_decode($response->getBody(), true);
print_r($data);

3.2 Handling XML Responses

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);

4. Error Handling in API Calls

Always handle timeouts, errors, and API failures.

4.1 Handling HTTP Errors

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();
}

4.2 Handling Timeouts

Set timeouts to prevent long delays:

$client = new Client([
    'timeout' => 5.0, // Timeout after 5 seconds
]);

4.3 Retrying Failed Requests

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]);

5. Best Practices for Consuming APIs in Yii2

  • Use Yii2 HTTP Client or Guzzle for easy API calls.
  • Cache API responses to improve performance.
  • Use authentication methods (API keys, OAuth, JWT).
  • Handle errors & timeouts to avoid crashes.
  • Log API responses for debugging.

Conclusion

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.