How to Build a REST API with PHP: A Complete Beginner’s Guide
REST APIs are one of the most common ways for web applications, mobile apps, and third-party services to communicate with a backend. PHP is an excellent choice for building REST APIs because it is widely supported, easy to deploy, and works well with databases such as MySQL.
In this guide, you’ll learn how to build a simple REST API using PHP, MySQL, and JSON, including CRUD operations for creating, reading, updating, and deleting data.
What Is a REST API?
A REST API, or Representational State Transfer Application Programming Interface, allows different applications to communicate over HTTP.
For example, a mobile application could request a list of products from a PHP API:
GET /api/products
The server could respond with JSON:
[
{
"id": 1,
"name": "Laptop",
"price": 125000
},
{
"id": 2,
"name": "Keyboard",
"price": 8500
}
]
Because REST APIs commonly use JSON, the same API can be consumed by websites, Android applications, iOS applications, desktop applications, and other backend services.
REST HTTP Methods
REST APIs typically use HTTP methods to represent different operations.
MethodPurposeExampleGETRetrieve data/api/productsPOSTCreate data/api/productsPUTUpdate data/api/products/1PATCHPartially update data/api/products/1DELETEDelete data/api/products/1
These operations are commonly referred to as CRUD:
- Create → POST
- Read → GET
- Update → PUT/PATCH
- Delete → DELETE
What We Will Build
For this tutorial, we'll create a simple Product REST API with the following endpoints:
GET /api/products GET /api/products/1 POST /api/products PUT /api/products/1 DELETE /api/products/1
The API will use:
- PHP
- MySQL
- PDO
- JSON
- HTTP methods
- HTTP status codes
Step 1: Create the Database
First, create a MySQL database.
CREATE DATABASE php_rest_api;
USE php_rest_api;
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(150) NOT NULL,
price DECIMAL(10,2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Add some sample products:
INSERT INTO products (name, price)
VALUES
('Laptop', 125000),
('Keyboard', 8500),
('Mouse', 4500);
Step 2: Create the Project Structure
A simple PHP REST API can use the following structure:
php-rest-api/ │ ├── config/ │ └── database.php │ ├── api/ │ └── products.php │ └── index.php
For a larger application, you can later separate controllers, models, middleware, authentication, validation, and routing.
Step 3: Create the Database Connection
Create:
config/database.php
Then add:
<?php
$host = 'localhost';
$db = 'php_rest_api';
$user = 'root';
$pass = '';
try {
$pdo = new PDO(
"mysql:host=$host;dbname=$db;charset=utf8mb4",
$user,
$pass
);
$pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Database connection failed'
]);
exit;
}
Using PDO gives us a safer and more flexible way to communicate with MySQL.
Step 4: Configure JSON Responses
Create:
api/products.php
Start with:
<?php
header('Content-Type: application/json');
require_once '../config/database.php';
$method = $_SERVER['REQUEST_METHOD'];
This tells the client that our API responses are JSON.
Step 5: Get All Products
We can use the GET method to retrieve all products.
if ($method === 'GET') {
$stmt = $pdo->query(
"SELECT id, name, price, created_at
FROM products
ORDER BY id DESC"
);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode([
'success' => true,
'data' => $products
]);
exit;
}
A request to:
GET /api/products.php
could return:
{
"success": true,
"data": [
{
"id": 3,
"name": "Mouse",
"price": "4500.00",
"created_at": "2026-09-14 00:00:00"
}
]
}
Step 6: Get a Single Product
We can use a query parameter to retrieve a specific product:
GET /api/products.php?id=1
PHP can read the ID:
$id = isset($_GET['id'])
? (int) $_GET['id']
: null;
Then query the database:
if ($method === 'GET' && $id) {
$stmt = $pdo->prepare(
"SELECT id, name, price, created_at
FROM products
WHERE id = ?"
);
$stmt->execute([$id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) {
http_response_code(404);
echo json_encode([
'success' => false,
'message' => 'Product not found'
]);
exit;
}
echo json_encode([
'success' => true,
'data' => $product
]);
exit;
}
Prepared statements are important because they help protect your application from SQL injection.
Step 7: Create a Product
To create a product, we'll use the POST method.
The client can send JSON such as:
{
"name": "Monitor",
"price": 65000
}
PHP can read the request body using:
$input = json_decode(
file_get_contents('php://input'),
true
);
Then validate the data:
if ($method === 'POST') {
$input = json_decode(
file_get_contents('php://input'),
true
);
if (
empty($input['name']) ||
!isset($input['price'])
) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'Name and price are required'
]);
exit;
}
$stmt = $pdo->prepare(
"INSERT INTO products (name, price)
VALUES (?, ?)"
);
$stmt->execute([
$input['name'],
$input['price']
]);
http_response_code(201);
echo json_encode([
'success' => true,
'message' => 'Product created successfully',
'id' => $pdo->lastInsertId()
]);
exit;
}
The 201 Created status code indicates that a new resource was successfully created.
Step 8: Update a Product
Use the PUT method to update an existing product.
if ($method === 'PUT' && $id) {
$input = json_decode(
file_get_contents('php://input'),
true
);
if (
empty($input['name']) ||
!isset($input['price'])
) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'Name and price are required'
]);
exit;
}
$stmt = $pdo->prepare(
"UPDATE products
SET name = ?, price = ?
WHERE id = ?"
);
$stmt->execute([
$input['name'],
$input['price'],
$id
]);
if ($stmt->rowCount() === 0) {
http_response_code(404);
echo json_encode([
'success' => false,
'message' => 'Product not found'
]);
exit;
}
echo json_encode([
'success' => true,
'message' => 'Product updated successfully'
]);
exit;
}
Step 9: Delete a Product
The DELETE method can remove a product.
if ($method === 'DELETE' && $id) {
$stmt = $pdo->prepare(
"DELETE FROM products
WHERE id = ?"
);
$stmt->execute([$id]);
if ($stmt->rowCount() === 0) {
http_response_code(404);
echo json_encode([
'success' => false,
'message' => 'Product not found'
]);
exit;
}
echo json_encode([
'success' => true,
'message' => 'Product deleted successfully'
]);
exit;
}
Step 10: Handle Unsupported Methods
It is good practice to return an appropriate HTTP status code when an unsupported method is used.
http_response_code(405);
echo json_encode([
'success' => false,
'message' => 'Method not allowed'
]);
The 405 Method Not Allowed response indicates that the requested HTTP method isn't supported by the endpoint.
Testing the API
You can test your API using tools such as Postman, Insomnia, curl, or JavaScript's Fetch API.
GET
curl http://localhost/php-rest-api/api/products.php
POST
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"Monitor","price":65000}' \
http://localhost/php-rest-api/api/products.php
PUT
curl -X PUT \
-H "Content-Type: application/json" \
-d '{"name":"Gaming Monitor","price":75000}' \
http://localhost/php-rest-api/api/products.php?id=1
DELETE
curl -X DELETE \ http://localhost/php-rest-api/api/products.php?id=1
Using the API with JavaScript
A frontend application can communicate with the PHP API using fetch().
For example:
fetch('/api/products.php')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
You can also create a product:
fetch('/api/products.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Web Camera',
price: 12000
})
})
.then(response => response.json())
.then(data => {
console.log(data);
});
This makes it possible to build modern web applications where PHP acts as the backend API while JavaScript, mobile apps, or other clients handle the frontend.
Important REST API Security Practices
A working API is only the beginning. Production APIs should also include security controls.
1. Use Prepared Statements
Avoid directly inserting user input into SQL queries.
Use:
$stmt = $pdo->prepare(
"SELECT * FROM products WHERE id = ?"
);
instead of constructing SQL with raw user input.
2. Validate Input
Never assume that data received from clients is valid.
Validate:
- Required fields
- Data types
- String length
- Numeric ranges
- Allowed values
3. Use Authentication
Private APIs should require authentication.
Common approaches include:
- API keys
- JWT
- OAuth 2.0
- Session-based authentication
4. Use HTTPS
Production APIs should use HTTPS to encrypt data transferred between the client and server.
5. Add Rate Limiting
Rate limiting can help protect APIs from abuse and excessive requests.
6. Avoid Exposing Sensitive Information
Do not return:
- Database passwords
- API secrets
- Internal server paths
- Stack traces
- Private user information
7. Configure CORS Carefully
If your frontend and API are hosted on different domains, configure Cross-Origin Resource Sharing (CORS) appropriately.
Avoid allowing every origin in production unless there is a specific reason.
Recommended API Response Format
A consistent response format makes APIs easier to consume.
For a successful request:
{
"success": true,
"data": {},
"message": "Request successful"
}
For an error:
{
"success": false,
"message": "Product not found",
"error": "RESOURCE_NOT_FOUND"
}
Consistency becomes especially important when your API grows to include dozens or hundreds of endpoints.
Organizing a Larger PHP REST API
For small projects, a single PHP file may be enough. However, larger applications should separate responsibilities.
A more scalable structure could look like:
api/
│
├── config/
│ └── database.php
│
├── controllers/
│ └── ProductController.php
│
├── models/
│ └── Product.php
│
├── middleware/
│ └── AuthMiddleware.php
│
├── routes/
│ └── api.php
│
├── helpers/
│ └── Response.php
│
└── public/
└── index.php
This approach makes the code easier to maintain as the application becomes more complex.
API Versioning
When an API is used by multiple applications, changing an existing endpoint can break older clients.
One common solution is API versioning:
/api/v1/products /api/v2/products
This allows you to introduce new functionality while maintaining compatibility with existing applications.
HTTP Status Codes You Should Know
Some commonly used status codes include:
StatusMeaning200OK201Created204No Content400Bad Request401Unauthorized403Forbidden404Not Found405Method Not Allowed422Unprocessable Content429Too Many Requests500Internal Server Error
Using appropriate HTTP status codes makes your API easier for developers to understand and integrate.
Conclusion
Building a REST API with PHP doesn't require a complicated framework. With PHP, MySQL, PDO, JSON, and standard HTTP methods, you can create a functional API that supports CRUD operations.
The basic workflow is:
Client ↓ HTTP Request ↓ PHP REST API ↓ Validation ↓ Database ↓ JSON Response ↓ Client
As your application grows, you can introduce authentication, middleware, routing, API versioning, rate limiting, caching, logging, and a more structured architecture.