← Back to Chapters

PHP REST API Introduction

? PHP REST API Introduction

? Quick Overview

A REST API (Representational State Transfer) is a way for two systems to communicate using the HTTP protocol. It allows clients such as browsers, mobile apps, or other servers to interact with a backend by sending requests and receiving structured responses, commonly in JSON format.

? Key Concepts

  • Client-server architecture
  • Stateless communication
  • Resource-based URLs
  • Standard HTTP methods

⚙️ How REST Works

  • Client sends an HTTP request (GET, POST, PUT, DELETE).
  • Server processes the request and performs the action.
  • Response is returned, usually in JSON format.

? Syntax / Theory

? View Code Example
// Common HTTP methods used in REST APIs
GET     → Retrieve data
POST    → Create new data
PUT     → Update existing data
DELETE  → Remove data
PATCH   → Update part of the resource

? Code Example: Simple REST API in PHP

? View Code Example
// Simple PHP REST API returning JSON data
<?php
header("Content-Type: application/json");

$users = [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"],
["id" => 3, "name" => "Charlie"]
];

if ($_SERVER["REQUEST_METHOD"] === "GET") {
echo json_encode($users);
}
?>

? Live Output / Explanation

? View Code Example
// Example GET request to fetch users
GET http://localhost/api/users
? View Code Example
// JSON response returned by the API
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" },
{ "id": 3, "name": "Charlie" }
]

? Interactive Understanding

This API can be tested interactively using tools like browser address bars, REST clients, or JavaScript fetch() calls to visualize real-time responses.

? Use Cases

  • Backend services for web applications
  • Mobile app data exchange
  • Microservices communication
  • Public or private API development

✅ Tips & Best Practices

  • Always return JSON for consistent API responses.
  • Use meaningful HTTP status codes.
  • Secure APIs using authentication methods like JWT or OAuth.

? Try It Yourself

  • Create an API that returns a list of books in JSON format.
  • Build a POST API to add a new user.
  • Experiment with PUT and DELETE to update and remove data.