JSON APIs

Serve JSON to React and mobile apps, and call other APIs with cURL.

React front ends and mobile apps talk to PHP through JSON. Send it with the right header and status code.

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

$jobs = [
    ["id" => 1, "title" => "PHP Intern", "city" => "Erode"],
    ["id" => 2, "title" => "React Intern", "city" => "Remote"],
];

$method = $_SERVER["REQUEST_METHOD"];

if ($method === "GET") {
    echo json_encode($jobs);
    exit;
}

if ($method === "POST") {
    $body = json_decode(file_get_contents("php://input"), true);
    if (!is_array($body) || trim($body["title"] ?? "") === "") {
        http_response_code(400);
        echo json_encode(["error" => "title is required"]);
        exit;
    }
    http_response_code(201);
    echo json_encode(["id" => 3, "title" => trim($body["title"])]);
    exit;
}

http_response_code(405);
echo json_encode(["error" => "Method not allowed"]);

JSON sent by fetch does not appear in $_POST. Read the raw body from php://input and decode it. Passing true to json_decode gives arrays instead of objects.

Calling another API

PHP
<?php
$ch = curl_init("https://api.example.com/rates");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("RATES_API_KEY")],
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($raw === false || $status !== 200) {
    error_log("Rates API failed with status $status");
    exit("Rates are not available right now.");
}
$rates = json_decode($raw, true);

Always set a timeout. Without one, a slow API makes your page hang until PHP gives up. Read keys from the environment, never from the code.

โ† Sessions and classesSecurity checklist โ†’