Cohere API API in PHP

Cohere API API in PHP

This guide shows you how to integrate the Cohere API into your PHP application. NLP platform for text generation, classification, embedding, and reranking with Command R models.

Prerequisites

  • PHP installed on your system
  • An Cohere API API key (sign up at https://cohere.ai)
  • Basic familiarity with HTTP APIs

Installation

composer require guzzlehttp/guzzle

Basic Usage

<?php
$apiKey = getenv('API_KEY') ?: 'YOUR_API_KEY';
$baseUrl = 'https://api.cohere.ai';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseUrl . '/v1/resources');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json',
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "Status: $httpCode\n";
echo $response . "\n";
?>

Error Handling

<?php
$apiKey = getenv('API_KEY') ?: 'YOUR_API_KEY';
$baseUrl = 'https://api.cohere.ai';

function callApiWithRetry($url, $headers, $maxRetries = 3) {
    $ch = curl_init();
    for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode === 429) {
            sleep(60);
            continue;
        }
        if ($httpCode < 500) {
            break;
        }
        sleep(pow(2, $attempt));
    }
    curl_close($ch);
    return [$httpCode, $response];
}

$url = $baseUrl . '/v1/resources';
$headers = ['Authorization: Bearer ' . $apiKey, 'Content-Type: application/json'];
list($code, $resp) = callApiWithRetry($url, $headers);
echo "Status: $code\n";
echo $resp . "\n";
?>

Advanced Usage

<?php
class CohereClient {
    private $apiKey;
    private $baseUrl;

    public function __construct($apiKey, $baseUrl = 'https://api.cohere.ai') {
        $this->apiKey = $apiKey;
        $this->baseUrl = rtrim($baseUrl, '/');
    }

    public function request($method, $path, $data = null) {
        $ch = curl_init();
        $url = $this->baseUrl . '/v1' . $path;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if ($data !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode >= 400) {
            throw new Exception("API Error: HTTP $httpCode");
        }
        return json_decode($response, true);
    }

    public function listResources($params = []) {
        $query = http_build_query($params);
        $path = '/resources' . ($query ? '?' . $query : '');
        return $this->request('GET', $path);
    }

    public function createResource($data) {
        return $this->request('POST', '/resources', $data);
    }
}

$client = new CohereClient(getenv('API_KEY') ?: 'YOUR_API_KEY');
$resources = $client->listResources(['limit' => 50]);
echo "Found " . count($resources['data'] ?? []) . " resources\n";
?>

Best Practices

  • Store your API key in an environment variable, never in source code
  • Implement retry logic with exponential backoff for 429 and 5xx errors
  • Set reasonable timeouts (10-30 seconds) for all API calls
  • Log request IDs from response headers for debugging
  • Cache responses where appropriate to reduce API calls

Other languages