← Back to Chapters

PHP REST API – Read Data

? PHP REST API – Read Data

? Quick Overview

This section demonstrates how to create a READ API in PHP using the GET method to retrieve records from a database and return them in JSON format.

? Key Concepts

  • RESTful API architecture
  • HTTP GET method
  • JSON data format
  • Database connectivity using MySQLi

? Syntax / Theory

A PHP READ API connects to a database, executes a SELECT query, converts the result into an array, and outputs JSON using proper headers.

? Code Example

? View Code Example
// Database connection and JSON response API
<?php
$host="localhost";
$user="root";
$pass="";
$dbname="rest_api";

$conn=new mysqli($host,$user,$pass,$dbname);

if($conn->connect_error){
die("Connection failed");
}

// Set JSON header
header("Content-Type: application/json");

$sql="SELECT id,name,email FROM users";
$result=$conn->query($sql);

$users=[];
while($row=$result->fetch_assoc()){
$users[]=$row;
}

// Return JSON output
echo json_encode($users);
$conn->close();
?>

? Live Output / Explanation

? View JSON Response
// Sample JSON response returned by the API
[
{"id":1,"name":"Alice","email":"alice@example.com"},
{"id":2,"name":"Bob","email":"bob@example.com"},
{"id":3,"name":"Charlie","email":"charlie@example.com"}
]

? Interactive Example

This API can be tested directly in the browser or using tools like Postman by accessing the PHP file URL.

? Use Cases

  • Fetching user data for dashboards
  • Providing backend data to frontend applications
  • Mobile app backend services

✅ Tips & Best Practices

  • Always return JSON with proper headers
  • Implement pagination for large datasets
  • Use HTTP status codes with responses

? Try It Yourself

  • Fetch a single user using query parameters
  • Add filtering by name or email
  • Consume the API using JavaScript fetch()