PHP REST API

Dharshitha Senevirathne
5 min readJun 28, 2024

--

Creating a REST API using PHP and MySQL provides a powerful way to interact with your database through simple HTTP requests. This guide will walk you through setting up a development environment using XAMPP, creating a MySQL database, building a PHP REST API, and testing it with Postman.

Step 1: Set Up XAMPP

Download and Install XAMPP

XAMPP is an open-source cross-platform web server solution stack package developed by Apache Friends, consisting mainly of the Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP and Perl programming languages. You can download XAMPP from the official website. The installation process is straightforward — just follow the on-screen instructions.

You can follow this to install XAMPP

Start Apache and MySQL

Once XAMPP is installed, open the XAMPP Control Panel. Here, you will see various services that XAMPP can manage. Start the Apache and MySQL services by clicking the ‘Start’ button next to each. These services are necessary for running your PHP scripts and managing your MySQL database.

Step 2: Create a MySQL Database

phpMyAdmin

phpMyAdmin is a free software tool written in PHP, intended to handle the administration of MySQL over the Web. It can perform various tasks such as creating, modifying, or deleting databases, tables, fields, or rows, executing SQL statements, or managing users and permissions. You can access phpMyAdmin by navigating to http://localhost/phpmyadmin in your web browser.

Create a Database

Within phpMyAdmin, you can create a new database:

  1. Click on the “New” link in the left sidebar.
  2. Enter a name for your database (e.g., users).
  3. Click “Create”.

Create a Table

With your new database selected:

  1. Click on the “New” link to create a new table.
  2. Name your table (e.g., users) and define the columns:
  • id (INT, Primary Key, Auto Increment)
  • name (VARCHAR(200))
  • email (VARCHAR(200))
  • Click “Save” to create the table.
users table

Step 3: Create the PHP REST API

A REST API is a web service that uses HTTP requests to perform CRUD operations on resources. It allows different software applications to communicate with each other over the web. REST APIs are used because they are stateless, scalable, and follow standard protocols.

What is an API endpoint?

An API endpoint is a specific URL where an API (Application Programming Interface) can be accessed by a client application. It represents a distinct route to a particular function or data set provided by the API.

Create a Project Folder

Navigate to the htdocs folder in your XAMPP installation directory (e.g., C:\xampp\htdocs). This is the web root directory for your local Apache server. Create a new folder for your project (e.g., restapi). This folder will contain all the files for your REST API.

Create a Database Connection File (db.php)

This file will handle the connection to your MySQL database. Using PDO (PHP Data Objects) is a good practice because it provides a consistent interface for accessing databases and is less prone to SQL injection attacks.

<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "users";

try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>

Create the API File (api.php)

This file will contain the logic for handling different types of HTTP requests (GET, POST, PUT, DELETE). Depending on the request method, the corresponding function will be called to perform the necessary database operations.

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

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
case 'GET':
handleGet($pdo);
break;
case 'POST':
handlePost($pdo, $input);
break;
case 'PUT':
handlePut($pdo, $input);
break;
case 'DELETE':
handleDelete($pdo, $input);
break;
default:
echo json_encode(['message' => 'Invalid request method']);
break;
}

function handleGet($pdo) {
$sql = "SELECT * FROM users";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}

function handlePost($pdo, $input) {
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['name' => $input['name'], 'email' => $input['email']]);
echo json_encode(['message' => 'User created successfully']);
}

function handlePut($pdo, $input) {
$sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['name' => $input['name'], 'email' => $input['email'], 'id' => $input['id']]);
echo json_encode(['message' => 'User updated successfully']);
}

function handleDelete($pdo, $input) {
$sql = "DELETE FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => $input['id']]);
echo json_encode(['message' => 'User deleted successfully']);
}
?>

Step 4: Test the API Using Postman

Start Postman

Postman is a popular tool for testing APIs. It allows you to send different types of HTTP requests to your API and see the responses. You can download Postman from the official website.

Test GET Request

To test retrieving data:

  1. Open Postman and create a new GET request.
  2. Enter the URL: http://localhost/restapi/api.php.
  3. Click “Send”. You should see a JSON response with all users in the database.
GET request

Test POST Request

To test adding new data:

  1. Create a new POST request.
  2. Enter the URL: http://localhost/restapi/api.php.
  3. Go to the “Body” tab, select “raw” and “JSON”.
  4. Enter the JSON data and click “Send”. You should see a success message.
{
"name": "John Doe",
"email": "john@example.com"
}
POST request

Test PUT Request

To test updating data:

  1. Create a new PUT request.
  2. Enter the URL: http://localhost/restapi/api.php.
  3. Go to the “Body” tab, select “raw” and “JSON”.
  4. Enter the JSON data and Click “Send”. You should see a success message.
{
"id": 1,
"name": "Jane Doe",
"email": "jane@example.com"
}

Test DELETE Request

To test deleting data:

  1. Create a new DELETE request.
  2. Enter the URL: http://localhost/restapi/api.php.
  3. Go to the “Body” tab, select “raw” and “JSON”.
  4. Enter the JSON data and click “Send”. You should see a success message.
{
"id": 1
}
DELETE Request

Conclusion

This guide has walked you through the process of setting up a REST API using PHP and MySQL with XAMPP. You learned how to create a MySQL database, build a PHP script to handle RESTful requests, and test the API using Postman. With these skills, you can now develop and test robust APIs for your web applications.

--

--

Dharshitha Senevirathne

My articles will help folks interested in software engineering, data science, and cloud technologies.