Skip to content

PHP API Client Examples

This section demonstrates how to send authenticated HTTP requests to the Core API using:

  • PHP’s built-in cURL extension
  • The popular Guzzle HTTP client library

Both examples perform a GET request using Bearer token authentication.


Base Configuration

Define your API configuration before making requests:

$baseUrl = "https://website.core-software.co.uk";
$token = "YOUR_TOKEN_HERE";

⚠️ Never hardcode API tokens in production environments. Use environment variables or a secure secrets manager instead.


Option 1: Using cURL

PHP cURL is included in most PHP installations and does not require additional dependencies.

Example Request

<?php

$baseUrl = "https://website.core-software.co.uk";
$token = "YOUR_TOKEN_HERE";

$ch = curl_init("$baseUrl/api/v1");

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $token",
        "Content-Type: application/json",
    ],
]);

$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

echo "Status: $status\n";
echo "Body: $response\n";

Notes (cURL)

  • No external dependencies are required
  • Suitable for lightweight or legacy applications
  • Response parsing and error handling must be implemented manually

Option 2: Using Guzzle

Guzzle is a modern HTTP client for PHP that simplifies API communication and error handling.

Installation

Install Guzzle using Composer:

composer require guzzlehttp/guzzle

Example

<?php

require "vendor/autoload.php";

use GuzzleHttp\Client;

$baseUrl = "https://website.core-software.co.uk";
$token = "YOUR_TOKEN_HERE";

$client = new Client([
    "base_uri" => $baseUrl,
]);

$response = $client->get("/api/v1", [
    "headers" => [
        "Authorization" => "Bearer $token",
        "Content-Type" => "application/json",
    ],
]);

echo "Status: " . $response->getStatusCode() . "\n";
echo "Body: " . $response->getBody() . "\n";

Why Use Guzzle?

  • Cleaner and more readable syntax
  • Built-in exception handling
  • PSR-7 compliant request and response handling
  • Reusable client configuration
  • Well suited for larger applications and services

Best Practices

  • Store API tokens securely using environment variables:
getenv("API_TOKEN");
  • Configure request timeouts
  • Handle exceptions using try/catch
  • Validate API responses before using returned data
  • Prefer reusable API client classes or service layers for larger applications