DEV Community

Cover image for How to Build a PHP REST API Step by Step
Eric Walter
Eric Walter

Posted on

How to Build a PHP REST API Step by Step

Ever thought about how your PHP applications communicate in the background? Whether it's linking your website with a mobile app, integrating third-party apps, or retrieving live data, PHP APIs streamline the whole process. To make this communication secure, efficient, high-performing, and maintainable, developers often prefer REST APIs. Moreover, they can handle lightweight apps to large platforms.

In this blog, we’ll learn how to set up REST PHP API in 7 easy steps. Additionally, why and when to hire dedicated PHP developers for seamless completion of your project.

Understanding PHP APIs and the Use of REST API

An API (Application Programming Interface) is a rule set that an application follows to transfer data. There are multiple APIs for PHP applications, some of them are REST API, SOAP API, GraphQL API, XML-RPC API, and JSON-RPC API. The process to set up each API in PHP is different because of the different architecture and use cases. The reasons why REST API is popular in PHP are as follows:

  • Easy to use and learn
  • Compatible with all hosting services
  • Effortlessly integrate with databases like MySQL
  • Use common HTTP methods such as GET, POST, PUT, and DELETE to carry out tasks

In terms of building REST APIs, Python vs PHP is often compared; however, PHP dominates because of its simplicity and more hosting options.

Essential Tools for Building a PHP REST API

Before you begin, make sure you have the following tools in your toolkit:

  • PHP latest version at least PHP 7.4
  • MySQL or MariaDB
  • Apache Server with mod_rewrite activated
  • Postman for API testing
  • Code editor like VS Code or PHPStorm

If you are still confused, it is always a good option to hire dedicated PHP developers who provide you with professional API development process.

Building REST APIs in PHP: A Simple Process

Here are a few easy steps with the help of which you can build a simple PHP REST API:

Step 01: Set Up the Project Structure

In your server directory, make a folder named php-rest-api by using this structure:

/php-rest-api 

  ├── index.php 

  ├── db.php 

  ├── .htaccess 

  └── /api 

       ├── get.php 

       ├── post.php 

       ├── put.php 

       └── delete.php 
Enter fullscreen mode Exit fullscreen mode

When you hire dedicated PHP developers for scaling or adding new features, they can use this file to easily manage and update code.

Step 02: Create Your Database

To build databases, use phpMyAdmin, MySQL CLI, or another database tool and make a table. In this case, we are taking an example of the “products” table for an e-commerce store:

CREATE DATABASE ecommerce_api; 

USE ecommerce_api; 

CREATE TABLE products (  

id INT AUTO_INCREMENT PRIMARY KEY,  

name VARCHAR(100) NOT NULL,  

price DECIMAL(10, 2) NOT NULL,  

description TEXT,  

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 

 ); 
Enter fullscreen mode Exit fullscreen mode

Step 03: Establish Connection to the Database (db.php)

Set up a MySQLi connection to reduce the chances of any error. For this step, you’ll write a code like:

<?php  

$host = "localhost";  

$username = "root"; // Replace with your DB username  

$password = ""; // Replace with your DB password  

$database = "ecommerce_api";  

$conn = new mysqli($host, $username, $password, $database);  

if ($conn->connect_error) {  

header('Content-Type: application/json');  

http_response_code(500);  

echo json_encode(["status" => "error", "message" => "Connection failed: " . $conn->connect_error]);  

exit;  

} 
Enter fullscreen mode Exit fullscreen mode

Furthermore, some PHP developers prefer PDO for e-commerce stores rather than MySQLi, but it depends on the project type and their expertise.

Step 04: Build API Endpoints

We’ll build PHP files that will manage different HTTP methods. Each file has a specific logic related to its task. The following are those files:

GET (get.php)

It will fetch all products for the public API and eliminate sensitive information.

<?php 

include '../db.php'; 

$sql = "SELECT * FROM users"; 

$result = $conn->query($sql); 

$data = []; 

while($row = $result->fetch_assoc()) { 

    $data[] = $row; 

} 

header('Content-Type: application/json'); 

echo json_encode($data); 

?> 

Enter fullscreen mode Exit fullscreen mode

POST (post.php)

It is for creating new products, with the help of prepared statements so to avoid SQL injection.

<?php  

header('Content-Type: application/json');  

require '../db.php';  

$data = json_decode(file_get_contents("php://input"), true);  

if (empty($data['name']) || empty($data['price'])) {  

echo json_encode(["error" => "Invalid input"]);  

exit;  

}  

$stmt = $conn->prepare("INSERT INTO products (name, price) VALUES (?, ?)");  

$stmt->bind_param("sd", $data['name'], $data['price']);  

$stmt->execute();  

echo json_encode(["message" => "Product added"]);  

$stmt->close();  

$conn->close();  

?> 

Enter fullscreen mode Exit fullscreen mode

PUT (put.php)

Its purpose is to update products and verify if ID is present.

<?php  

header('Content-Type: application/json');  

require '../db.php';  

$data = json_decode(file_get_contents("php://input"), true);  

if (empty($data['id']) || empty($data['name']) || empty($data['price'])) {  

echo json_encode(["error" => "Invalid input"]);  

exit;  

}  

$stmt = $conn->prepare("UPDATE products SET name = ?, price = ? WHERE id = ?");  

$stmt->bind_param("sdi", $data['name'], $data['price'], $data['id']);  

$stmt->execute();  

echo json_encode(["message" => $stmt->affected_rows ? "Product updated": "Product not found"]);  

$stmt->close();  

$conn->close(); 

Enter fullscreen mode Exit fullscreen mode

DELETE (delete.php)

It is to remove any product.

<?php  

header('Content-Type: application/json');  

require '../db.php';  

$data = json_decode(file_get_contents("php://input"), true);  

if (empty($data['id'])) {  

echo json_encode(["error" => "Invalid ID"]);  

exit;  

}  

$stmt = $conn->prepare("DELETE FROM products WHERE id = ?");  

$stmt->bind_param("i", $data['id']);  

$stmt->execute();  

echo json_encode(["message" => $stmt->affected_rows ? "Product deleted": "Product not found"]);  

$stmt->close();  

$conn->close(); 

Enter fullscreen mode Exit fullscreen mode

Step 05: Route Requests with index.php

This step is essential to resolve where the request is coming from (GET, POST, PUT, or DELETE) and send it to the right section of your code.

<?php  

header('Content-Type: application/json');  

$request = $_SERVER['REQUEST_METHOD'];  

switch ($request) {  

case 'GET':  

require 'api/get.php';  

break;  

Case 'POST':  

require 'api/post.php';  

break;  

Case 'PUT':  

require 'api/put.php';  

break;  

Case 'DELETE':  

require 'api/delete.php';  

break;  

default:  

http_response_code(405);  

echo json_encode(["status" => "error", "message" => "Invalid request method"]);  

}  

?> 
Enter fullscreen mode Exit fullscreen mode

Step 06: Activate URL Rewriting in .htaccess File

Clean URLs are important for public e-commerce APIs, so enable them with Apache’s mod_rewrite module, like:

RewriteEngine On  

RewriteCond %{REQUEST_FILENAME} !-f  

RewriteCond %{REQUEST_FILENAME} !-d  

RewriteRule ^ index.php [QSA,L] 
Enter fullscreen mode Exit fullscreen mode

Step 07: Test your API

There are different tools used to test PHP APIs such as Postman:

GET – View all products: http://localhost/php-rest-api/api/get.php 

POST – Add a product: {"name":"Phone","price":499.99} 

PUT – Update a product: {"id":1,"name":"Phone Pro","price":599.99} 

DELETE – Remove a product: {"id":1} 

And expect a response like “{"message":"Product deleted"}”  
Enter fullscreen mode Exit fullscreen mode

Extra Tip- Add Basic Error Handling & Validation

To make sure that your PHP REST API is secure, reliable, and simple, check the following points:

  • Validate inputs such as the name and price of the products are correctly provided
  • Prevent SQL injection by using MySQL prepared statements
  • Apply HTTP status codes like 200 (success), 400 (bad request), or 404 (not found)

Verifying and using these tools will result in high-quality code and reduce the chances of errors during deployment.

When to Hire Dedicated React Developers?

Building simple applications is an easy task; however, when you are growing, it might seem difficult. So, you should consider to hire dedicated PHP developers in the following cases:

  • When you demand complex features like live syncing of data, third-party integrations, or addition of payment gateways
  • Performance and faster response are your priorities
  • Shifting to mobile or web apps with scalable backend
  • No experienced team or developers to manage backend development

Always try to reach trusted agencies like Bizmia, who provide experienced teams and developers to make your PHP API development smooth.

Final Thoughts

Building a PHP REST API is an essential step to move towards modern web development. However, it is important to follow the right tools, practices, and methods for a successful PHP REST API development. You must consider your project goals and expertise before starting the process, and if you lack something, it is always recommended to hire PHP developers who leverage all security measures and follow the process correctly.

Top comments (1)

Collapse
 
eastcoast8264 profile image
Mark M • Edited

Thanks for the post! Very informative.

Couple notes:

  • Please stop using inline comments. While desktop displays have a good amount of width, mobile displays do not and improperly formatted code can result some comments being only partially visible (with a lot of horizontal scrolling) or missed entirely.
    • Everyone reads code top-to-bottom, so we should know what the comment is referring to. If not, then refactor the code and update variable names to ensure someone viewing the code for the first time won't struggle too much with understanding it, which includes sensible commentary.
  • The last section heading, "When to Hire Dedicated React Developers?" uses React my mistake.