Web Analytics

PHP APIs & JSON

Advanced~30 min read

APIs enable communication between applications. Learn to consume external APIs and create your own using JSON - the standard data format for web services!

Output
Click Run to execute your code

Fetch API Data with cURL

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/users');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
?>

POST Request

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/users');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'name' => 'John',
    'email' => '[email protected]'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
?>

Create Simple API

<?php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode(['users' => [
        ['id' => 1, 'name' => 'John'],
        ['id' => 2, 'name' => 'Jane']
    ]]);
}
?>

Summary

  • cURL: Make HTTP requests
  • json_encode(): PHP to JSON
  • json_decode(): JSON to PHP
  • REST API: Standard web service pattern

What's Next?

Next, learn about Security Best Practices - protecting your applications!