PHP and APIs

Learn how to create and consume APIs using PHP.

Creating a Simple API with PHP

APIs (Application Programming Interfaces) allow different applications to communicate with each other. PHP can be used to create APIs that provide data to other applications.

Step1: Setting Up the API Endpoint

First, you need to set up a PHP script that will act as the API endpoint.

// api.php
header('Content-Type: application/json');
$data = array('message' => 'Hello, World!');
echo json_encode($data);
 

Step2: Consuming the API

You can consume the API using PHP's curl functions or other HTTP client libraries.

// consume_api.php
$url = 'http://example.com/api.php';
$response = json_decode(file_get_contents($url), true);
echo $response['message'];
 

Step3: Handling API Requests

You can handle different types of API requests (e.g., GET, POST) and process the data accordingly.

// handle_request.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
 $data = json_decode(file_get_contents('php://input'), true);
 // Process the data
 echo json_encode(array('message' => 'Data received'));
}
 

API Example: User Data

This API endpoint returns user data in JSON format.

// user_api.php
header('Content-Type: application/json');
$users = array(
 array('id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'),
 array('id' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com')
);
echo json_encode($users);
 

Try it Yourself!

API Quiz