Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, 31 March 2026

🚀 How to Build a REST API Using PHP (Beginner Friendly Guide)

                                     


📌 Introduction

If you're starting your journey in web development, learning how to build a REST API in PHP is one of the most valuable skills you can have. APIs allow different systems to communicate — from mobile apps to web dashboards.

In this guide, we’ll walk through a simple way to create your own API using PHP.


🧠 What is a REST API?

A REST API (Representational State Transfer) is a way for applications to communicate using HTTP methods like:

  • GET → Retrieve data
  • POST → Create data
  • PUT → Update data
  • DELETE → Remove data

👉 Example:

GET /api/users

🛠️ Requirements

Before we start, make sure you have:

  • PHP installed (XAMPP / Hostinger / VPS)
  • Basic knowledge of PHP
  • A database (MySQL or PostgreSQL)

⚡ Step 1: Create Your Database

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);

⚡ Step 2: Create Database Connection (db.php)

<?php
$conn = new mysqli("localhost", "root", "", "test_db");

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

⚡ Step 3: Create API File (api.php)

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

$method = $_SERVER['REQUEST_METHOD'];

switch($method) {

case 'GET':
$result = $conn->query("SELECT * FROM users");
$data = [];

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

echo json_encode($data);
break;

case 'POST':
$input = json_decode(file_get_contents("php://input"), true);
$name = $input['name'];
$email = $input['email'];

$conn->query("INSERT INTO users (name, email) VALUES ('$name', '$email')");
echo json_encode(["message" => "User added"]);
break;

case 'DELETE':
$id = $_GET['id'];
$conn->query("DELETE FROM users WHERE id=$id");
echo json_encode(["message" => "User deleted"]);
break;

default:
echo json_encode(["message" => "Invalid request"]);
}
?>

🧪 How to Test Your API

You can test your API using:

  • Postman
  • Browser (for GET requests)
  • Axios (JavaScript frontend)

👉 Example request:

GET http://localhost/api.php

🔒 Important Tips

  • Always sanitize inputs (to avoid SQL injection)
  • Use prepared statements in production
  • Add authentication (JWT or API keys)
comments