How to Create and Consume PHP REST APIs

This article provides a straightforward guide on how to build and consume RESTful APIs using PHP. You will learn how to set up a simple API endpoint that processes HTTP requests and returns JSON responses, as well as how to use PHP’s cURL extension to request and consume data from external API endpoints.

Creating a RESTful API in PHP

To create a RESTful API in PHP, you need to handle incoming HTTP requests, determine the request method (GET, POST, PUT, DELETE), process the data, and return a response in a standard format like JSON.

1. Set the Response Headers

Your PHP script must tell the client that it is returning JSON data. Use the header() function to set the content type and CORS (Cross-Origin Resource Sharing) policies if necessary.

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");

2. Detect the HTTP Request Method

You can determine how the client is accessing your API using the $_SERVER['REQUEST_METHOD'] variable.

$request_method = $_SERVER['REQUEST_METHOD'];

switch ($request_method) {
    case 'GET':
        handleGet();
        break;
    case 'POST':
        handlePost();
        break;
    default:
        http_response_code(405);
        echo json_encode(["message" => "Method Not Allowed"]);
        break;
}

3. Handle the Request and Return JSON

When sending data back to the client, use http_response_code() to set the appropriate HTTP status code (e.g., 200 for Success, 201 for Created, 404 for Not Found) and json_encode() to format your output.

function handleGet() {
    $data = [
        ["id" => 1, "name" => "Product A", "price" => 10.99],
        ["id" => 2, "name" => "Product B", "price" => 20.99]
    ];
    
    http_response_code(200);
    echo json_encode($data);
}

function handlePost() {
    // Read the raw input stream for JSON payload
    $input = json_decode(file_get_contents("php://input"), true);
    
    if (!empty($input['name']) && !empty($input['price'])) {
        http_response_code(201);
        echo json_encode([
            "message" => "Product created successfully.",
            "data" => $input
        ]);
    } else {
        http_response_code(400);
        echo json_encode(["message" => "Incomplete data."]);
    }
}

Consuming a RESTful API in PHP

To consume a RESTful API from a PHP application, you send HTTP requests to an external server. The most robust way to do this in PHP is by using the cURL extension.

1. Making a GET Request

To retrieve data from an API, initialize a cURL session, set the target URL, and execute the request.

$url = "https://api.example.com/products";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    $data = json_decode($response, true);
    print_r($data);
}

curl_close($ch);

2. Making a POST Request

To send data to an API, you must configure cURL to use the POST method, attach the payload, and set the appropriate headers.

$url = "https://api.example.com/products";
$data = [
    "name" => "New Product",
    "price" => 15.49
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_API_TOKEN'
]);

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

if ($http_code === 201) {
    echo "Resource successfully created: " . $response;
} else {
    echo "Failed with status code: " . $http_code;
}

curl_close($ch);