In this tutorial, you’ll learn how to create a REST API in PHP without using a framework. This approach is ideal for those who want a lightweight and straightforward solution for API development. Follow these steps to build a simple and functional REST API.
What Is a REST API?
A REST API (Representational State Transfer Application Programming Interface) enables communication between a client and a server through HTTP methods like GET, POST, PUT, and DELETE. REST APIs are widely used for web and mobile app development, allowing seamless data exchange.
Why Create a REST API Without a Framework?
Frameworks like Laravel or Symfony provide robust solutions for API development, but they come with added complexity. For small-scale projects or when you want to maintain full control over your code, creating a REST API without a framework can be a practical choice.
Steps to Build a REST API in PHP
Step 1: Set Up Your Environment
Before diving into coding, ensure your development environment is ready.
- Install PHP: Make sure PHP is installed on your system. Use
php -v
in your terminal to check the version. - Set Up a Local Server: Use tools like XAMPP, WAMP, or the built-in PHP server (
php -S localhost:8000
). - Create a Project Folder: Organize your files. For example, create a folder named
php-api
to store your API code.
Step 2: Create the API Endpoint
An API endpoint is a URL that allows clients to interact with your API. Start by creating a basic structure:
- Define the API entry point: Create a file named
api.php
in your project folder. - Set up routing: Use a
$_SERVER
global variable to handle different HTTP methods like GET, POST, PUT, and DELETE.
Here’s an example code snippet:
<?php
header("Content-Type: application/json");
$requestMethod = $_SERVER['REQUEST_METHOD'];
switch ($requestMethod) {
case 'GET':
handleGetRequest();
break;
case 'POST':
handlePostRequest();
break;
default:
echo json_encode(["message" => "Method not allowed"]);
http_response_code(405);
break;
}
function handleGetRequest() {
echo json_encode(["message" => "This is a GET request"]);
}
function handlePostRequest() {
echo json_encode(["message" => "This is a POST request"]);
}
?>
Step 3: Connect to a Database
APIs often interact with databases to retrieve or store data. Let’s Connect to a MySQL database using PHP’s PDO (PHP Data Objects).
<?php
function connectToDatabase() {
$host = 'localhost';
$db = 'example_db';
$user = 'root';
$pass = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
die(json_encode(["error" => "Database connection failed", "message" => $e->getMessage()]));
}
}
?>
Step 4: Add CRUD Operations
CRUD (Create, Read, Update, Delete) operations are the foundation of most APIs. Here’s how to implement them:
Create (POST): Add Data
function addData($pdo, $data) {
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute([":name" => $data['name'], ":email" => $data['email']]);
return ["message" => "Data added successfully"];
}
Read (GET): Fetch Data
function fetchData($pdo) {
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
Update (PUT): Modify Data
function updateData($pdo, $id, $data) {
$sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([":name" => $data['name'], ":email" => $data['email'], ":id" => $id]);
return ["message" => "Data updated successfully"];
}
Delete (DELETE): Remove Data
function deleteData($pdo, $id) {
$sql = "DELETE FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([":id" => $id]);
return ["message" => "Data deleted successfully"];
}
Step 5: Test Your API
Use tools like Postman or cURL to test your API endpoints.
- GET Request:
http://localhost/php-api/api.php
- POST Request: Send a JSON payload like
{"name": "John Doe", "email": "john@example.com"}
. - PUT and DELETE Requests: Include the resource ID and relevant data.
Example Use Case
Imagine a mobile app that requires user data. By creating a REST API, you can serve this data efficiently and securely, enabling features like user registration, updates, and more.
Benefits of a Custom REST API
- Lightweight and faster compared to framework-based APIs.
- Full control over implementation.
- Tailored to specific project needs.
Conclusion
This tutorial provides a starting point for building a PHP REST API without using a framework. While frameworks can simplify large projects, custom APIs are ideal for lightweight solutions. Try enhancing this API with additional features like authentication, pagination, or logging.
What’s Next?
- Ready to start building your own REST API?
- Add authentication for secure API access.
- Implement advanced features like pagination, filtering, or rate limiting.
Have questions about this tutorial? Leave a comment below or share your experiences with building APIs in PHP!