REST API with PHP


REST API (Representational State Transfer) represents a web service that utilizes standard HTTP methods like GET, POST, PUT, DELETE to enable client interaction with data. Web and mobile applications typically use it to perform data reading and manipulation through HTTP communication.

php-rest-api

REST API

HTTP Method Purpose PHP Action
GET Retrieve data Read from DB
POST Create data Insert into DB
PUT Update data Update in DB
DELETE Delete data Remove from DB

db.php – Database Connection

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?> 

index.php – REST API Endpoint

<?php
header("Content-Type: application/json");
include 'db.php';

$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
    case 'GET':
        // READ
        $stmt = $pdo->query("SELECT * FROM products");
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($products);
        break;

    case 'POST':
        // CREATE
        $input = json_decode(file_get_contents("php://input"), true);
        $stmt = $pdo->prepare("INSERT INTO products (name, price) VALUES (?, ?)");
        $stmt->execute([$input['name'], $input['price']]);
        echo json_encode(["message" => "Product created"]);
        break;

    case 'PUT':
        // UPDATE
        parse_str(file_get_contents("php://input"), $input);
        $stmt = $pdo->prepare("UPDATE products SET name=?, price=? WHERE id=?");
        $stmt->execute([$input['name'], $input['price'], $input['id']]);
        echo json_encode(["message" => "Product updated"]);
        break;

    case 'DELETE':
        // DELETE
        parse_str(file_get_contents("php://input"), $input);
        $stmt = $pdo->prepare("DELETE FROM products WHERE id=?");
        $stmt->execute([$input['id']]);
        echo json_encode(["message" => "Product deleted"]);
        break;

    default:
        http_response_code(405);
        echo json_encode(["error" => "Method Not Allowed"]);
        break;
}
?> 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.