SyntaxStudy
Sign Up
PHP Consuming REST APIs in PHP
PHP Intermediate 5 min read

Consuming REST APIs in PHP

Consuming REST APIs

Use file_get_contents() with context for simple GET requests, or the cURL extension for full HTTP control. Guzzle is a popular HTTP client library.

Example
<?php
// Simple GET with file_get_contents
$context = stream_context_create([
    "http" => ["header" => "Authorization: Bearer " . $token]
]);
$response = file_get_contents("https://api.example.com/users", false, $context);
$users = json_decode($response, true, 512, JSON_THROW_ON_ERROR);

// POST with cURL
$ch = curl_init("https://api.example.com/users");
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode(["name" => "Alice"]),
    CURLOPT_HTTPHEADER     => ["Content-Type: application/json"],
    CURLOPT_RETURNTRANSFER => true,
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
Pro Tip

Use Guzzle for production HTTP requests — it handles retries, timeouts, middleware, and async requests cleanly.