|
|
Line 1: |
Line 1: |
− | Berikut adalah modul "Membuat dan Mengonsumsi API Sederhana dengan PHP" sebagai bagian dari mata kuliah Pemrograman Web, dengan fokus pada pengantar RESTful API menggunakan Ubuntu 24.04. Modul ini mencakup langkah-langkah praktis dan contoh implementasi tanpa menggunakan alat dari Microsoft. | + | Berikut modul lengkap berjudul **"Membuat dan Mengonsumsi API Sederhana dengan PHP di Ubuntu 24.04"**. Modul ini cocok untuk pemula yang ingin belajar dasar API menggunakan PHP dan dijalankan di Ubuntu 24.04. |
| | | |
− | ## Pendahuluan
| + | --- |
| | | |
− | RESTful API (Representational State Transfer) adalah arsitektur yang memungkinkan komunikasi antara klien dan server melalui protokol HTTP. Dalam modul ini, kita akan membahas cara membuat API sederhana menggunakan PHP dan MySQL, serta bagaimana mengonsumsi API tersebut.
| + | ## 🧩 Modul: Membuat dan Mengonsumsi API Sederhana dengan PHP di Ubuntu 24.04 |
| | | |
− | ## 1. Persiapan Lingkungan | + | ### 🎯 Tujuan Pembelajaran |
| + | - Memahami konsep dasar REST API. |
| + | - Membangun API sederhana dengan PHP (tanpa framework). |
| + | - Mengonsumsi (mengakses) API menggunakan PHP dan tools seperti `curl`. |
| + | - Menjalankan API di server lokal Ubuntu 24.04 (menggunakan Apache). |
| | | |
− | ### 1.1. Instalasi Apache, MySQL, dan PHP
| + | --- |
| | | |
− | Pastikan sistem Ubuntu 24.04 Anda telah terinstal Apache, MySQL, dan PHP (LAMP stack). Jika belum, Anda dapat menginstalnya dengan perintah berikut:
| + | ## 🛠️ Persiapan Lingkungan |
| | | |
| + | ### 1. Install Apache, PHP, dan cURL |
| ```bash | | ```bash |
| sudo apt update | | sudo apt update |
− | sudo apt install apache2 mysql-server php libapache2-mod-php php-mysql -y | + | sudo apt install apache2 php libapache2-mod-php php-curl |
| ``` | | ``` |
− |
| |
− |
| |
− | Setelah instalasi, amankan MySQL dengan menjalankan:
| |
− |
| |
− | ```bash
| |
− | sudo mysql_secure_installation
| |
− | ```
| |
− |
| |
− |
| |
− | ### 1.2. Konfigurasi Direktori Proyek
| |
− |
| |
− | Buat direktori untuk proyek Anda di direktori root web server:
| |
− |
| |
− | ```bash
| |
− | sudo mkdir /var/www/html/restful-api
| |
− | sudo chown -R $USER:$USER /var/www/html/restful-api
| |
− | ```
| |
− |
| |
− |
| |
− | ## 2. Membuat Database dan Tabel
| |
− |
| |
− | ### 2.1. Membuat Database
| |
− |
| |
− | Masuk ke MySQL dan buat database baru:
| |
| | | |
| + | ### 2. Buat Folder Project |
| ```bash | | ```bash |
− | mysql -u root -p
| + | sudo mkdir -p /var/www/html/simple-api |
− | ```
| + | sudo chown -R $USER:$USER /var/www/html/simple-api |
− |
| + | cd /var/www/html/simple-api |
− | | |
− | Setelah masuk ke prompt MySQL, jalankan:
| |
− | | |
− | ```sql
| |
− | CREATE DATABASE db_api;
| |
− | USE db_api;
| |
| ``` | | ``` |
− |
| |
| | | |
− | ### 2.2. Membuat Tabel
| + | --- |
| | | |
− | Buat tabel `products` dengan struktur berikut:
| + | ## 📦 Bagian 1: Membuat API Sederhana |
| | | |
− | ```sql
| + | ### 1.1 Struktur Direktori |
− | CREATE TABLE products (
| |
− | id INT AUTO_INCREMENT PRIMARY KEY,
| |
− | name VARCHAR(100) NOT NULL,
| |
− | description TEXT,
| |
− | price DECIMAL(10, 2) NOT NULL,
| |
− | created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
| |
− | );
| |
| ``` | | ``` |
− |
| + | simple-api/ |
− | | + | ├── api.php |
− | ## 3. Membuat API dengan PHP
| + | └── data.json |
− | | |
− | ### 3.1. Struktur Proyek
| |
− | | |
− | Atur struktur direktori proyek Anda sebagai berikut:
| |
− | | |
| ``` | | ``` |
| | | |
− | restful-api/
| + | ### 1.2 Isi `data.json` |
− | ├── api
| + | ```json |
− | │ ├── config
| + | [ |
− | │ │ └── Database.php
| + | {"id": 1, "name": "Alice"}, |
− | │ ├── objects
| + | {"id": 2, "name": "Bob"}, |
− | │ │ └── Product.php
| + | {"id": 3, "name": "Charlie"} |
− | │ ├── product
| + | ] |
− | │ │ ├── create.php
| |
− | │ │ ├── delete.php
| |
− | │ │ ├── read.php
| |
− | │ │ ├── read_one.php
| |
− | │ │ └── update.php
| |
− | │ └── index.php
| |
− | └── .htaccess
| |
− | ```
| |
− |
| |
− | | |
− | ### 3.2. Konfigurasi Database | |
− | | |
− | Buat file `Database.php` di direktori `api/config` dengan isi berikut:
| |
− | | |
− | ```php | |
− | <?php
| |
− | class Database {
| |
− | private $host = "localhost";
| |
− | private $db_name = "db_api";
| |
− | private $username = "root";
| |
− | private $password = ""; | |
− | public $conn;
| |
− | | |
− | public function getConnection() {
| |
− | $this->conn = null;
| |
− | try {
| |
− | $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
| |
− | $this->conn->exec("set names utf8");
| |
− | } catch (PDOException $exception) {
| |
− | echo "Koneksi error: " . $exception->getMessage();
| |
− | }
| |
− | return $this->conn;
| |
− | }
| |
− | } | |
− | ?>
| |
| ``` | | ``` |
− |
| |
− |
| |
− | ### 3.3. Membuat Model Produk
| |
− |
| |
− | Buat file `Product.php` di direktori `api/objects` dengan isi berikut:
| |
| | | |
| + | ### 1.3 Isi `api.php` |
| ```php | | ```php |
| <?php | | <?php |
− | class Product {
| + | header('Content-Type: application/json'); |
− | private $conn;
| |
− | private $table_name = "products";
| |
− | | |
− | public $id;
| |
− | public $name;
| |
− | public $description;
| |
− | public $price;
| |
− | public $created_at;
| |
− | | |
− | public function __construct($db) {
| |
− | $this->conn = $db;
| |
− | }
| |
− | | |
− | function read() {
| |
− | $query = "SELECT id, name, description, price, created_at FROM " . $this->table_name . " ORDER BY created_at DESC";
| |
− | $stmt = $this->conn->prepare($query);
| |
− | $stmt->execute();
| |
− | return $stmt;
| |
− | }
| |
− | | |
− | function create() {
| |
− | $query = "INSERT INTO " . $this->table_name . " SET name=:name, description=:description, price=:price";
| |
− | $stmt = $this->conn->prepare($query);
| |
| | | |
− | $this->name = htmlspecialchars(strip_tags($this->name));
| + | $data = json_decode(file_get_contents('data.json'), true); |
− | $this->description = htmlspecialchars(strip_tags($this->description));
| |
− | $this->price = htmlspecialchars(strip_tags($this->price));
| |
| | | |
− | $stmt->bindParam(":name", $this->name);
| + | if ($_SERVER['REQUEST_METHOD'] === 'GET') { |
− | $stmt->bindParam(":description", $this->description); | + | if (isset($_GET['id'])) { |
− | $stmt->bindParam(":price", $this->price); | + | $id = intval($_GET['id']); |
− | | + | foreach ($data as $item) { |
− | if ($stmt->execute()) {
| + | if ($item['id'] === $id) { |
− | return true; | + | echo json_encode($item); |
| + | exit; |
| + | } |
| } | | } |
− | return false;
| + | echo json_encode(["error" => "Data not found"]); |
− | }
| |
− | | |
− | function readOne() {
| |
− | $query = "SELECT id, name, description, price, created_at FROM " . $this->table_name . " WHERE id = ? LIMIT 0,1";
| |
− | $stmt = $this->conn->prepare($query);
| |
− | $stmt->bindParam(1, $this->id);
| |
− | $stmt->execute();
| |
− | | |
− | $row = $stmt->fetch(PDO::FETCH_ASSOC);
| |
− | if ($row) {
| |
− | $this->name = $row['name'];
| |
− | $this->description = $row['description'];
| |
− | $this->price = $row['price'];
| |
− | $this->created_at = $row['created_at'];
| |
− | return true;
| |
− | }
| |
− | return false;
| |
− | }
| |
− | | |
− | function update() {
| |
− | $query = "UPDATE " . $this->table_name . " SET name = :name, description = :description, price = :price WHERE id = :id";
| |
− | $stmt = $this->conn->prepare($query);
| |
− | | |
− | $this->name = htmlspecialchars(strip_tags($this->name));
| |
− | $this->description = htmlspecialchars(strip_tags($this->description));
| |
− | $this->price = htmlspecialchars(strip_tags($this->price));
| |
− | $this->
| |
− | | |
− | | |
− | | |
− | | |
− | | |
− | | |
− | | |
− | Melanjutkan modul sebelumnya tentang "Membuat dan Mengonsumsi API Sederhana dengan PHP" pada mata kuliah Pemrograman Web, berikut adalah langkah-langkah tambahan untuk melengkapi implementasi RESTful API dengan operasi **Update** dan **Delete**, serta cara mengonsumsi API tersebut menggunakan PHP di lingkungan Ubuntu 24.04.
| |
− | | |
− | ## 4. Menambahkan Operasi Update dan Delete pada API
| |
− | | |
− | ### 4.1. Endpoint Update (PUT)
| |
− | | |
− | Buat file `update.php` di direktori `api/product` dengan isi berikut:
| |
− | | |
− | | |
− | ```php
| |
− | <?php
| |
− | // Header yang diperlukan
| |
− | header("Access-Control-Allow-Origin: *");
| |
− | header("Content-Type: application/json; charset=UTF-8");
| |
− | header("Access-Control-Allow-Methods: PUT");
| |
− | header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
| |
− | | |
− | // Sertakan file yang diperlukan
| |
− | include_once '../config/Database.php';
| |
− | include_once '../objects/Product.php';
| |
− | | |
− | // Dapatkan koneksi database
| |
− | $database = new Database();
| |
− | $db = $database->getConnection();
| |
− | | |
− | // Persiapkan objek produk
| |
− | $product = new Product($db);
| |
− | | |
− | // Dapatkan data yang dikirim
| |
− | $data = json_decode(file_get_contents("php://input"));
| |
− | | |
− | // Pastikan data yang diperlukan tersedia
| |
− | if (!empty($data->id) && (!empty($data->name) || !empty($data->description) || !empty($data->price))) {
| |
− | // Set ID produk yang akan diperbarui
| |
− | $product->id = $data->id;
| |
− | | |
− | // Set properti produk berdasarkan data yang tersedia
| |
− | if (!empty($data->name)) {
| |
− | $product->name = $data->name;
| |
− | }
| |
− | if (!empty($data->description)) {
| |
− | $product->description = $data->description;
| |
− | }
| |
− | if (!empty($data->price)) {
| |
− | $product->price = $data->price;
| |
− | }
| |
− | | |
− | // Perbarui produk
| |
− | if ($product->update()) {
| |
− | // Set respons kode 200 - OK
| |
− | http_response_code(200);
| |
− | echo json_encode(array("message" => "Produk berhasil diperbarui.")); | |
| } else { | | } else { |
− | // Set respons kode 503 - Service Unavailable
| + | echo json_encode($data); |
− | http_response_code(503);
| |
− | echo json_encode(array("message" => "Gagal memperbarui produk.")); | |
| } | | } |
| } else { | | } else { |
− | // Set respons kode 400 - Bad Request
| + | echo json_encode(["error" => "Method not supported"]); |
− | http_response_code(400);
| |
− | echo json_encode(array("message" => "Data tidak lengkap.")); | |
| } | | } |
− | ?>
| |
| ``` | | ``` |
− |
| |
− |
| |
− | **Penjelasan:**
| |
| | | |
− | - **Header HTTP:** Menentukan bahwa metode yang diizinkan adalah PUT dan mengatur tipe konten sebagai JSON. | + | ### 1.4 Akses API via Browser |
− | - **Membaca Input:** Mengambil data JSON yang dikirim oleh klien. | + | - Semua data: [http://localhost/simple-api/api.php](http://localhost/simple-api/api.php) |
− | - **Validasi Data:** Memastikan bahwa ID produk dan setidaknya satu atribut lainnya disertakan dalam permintaan. | + | - Data berdasarkan ID: [http://localhost/simple-api/api.php?id=2](http://localhost/simple-api/api.php?id=2) |
− | - **Memperbarui Produk:** Memanggil metode `update()` pada objek produk untuk memperbarui data di database. | |
| | | |
− | ### 4.2. Endpoint Delete (DELETE)
| + | --- |
− | | |
− | Buat file `delete.php` di direktori `api/product` dengan isi berikut:
| |
| | | |
| + | ## 📥 Bagian 2: Mengonsumsi API dengan PHP |
| | | |
| + | ### 2.1 File: `consume.php` |
| ```php | | ```php |
| <?php | | <?php |
− | // Header yang diperlukan
| + | function getData($url) { |
− | header("Access-Control-Allow-Origin: *");
| + | $ch = curl_init(); |
− | header("Content-Type: application/json; charset=UTF-8");
| + | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
− | header("Access-Control-Allow-Methods: DELETE");
| + | curl_setopt($ch, CURLOPT_URL, $url); |
− | header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
| + | $result = curl_exec($ch); |
| + | curl_close($ch); |
| + | return json_decode($result, true); |
| + | } |
| | | |
− | // Sertakan file yang diperlukan | + | $apiUrl = "http://localhost/simple-api/api.php"; |
− | include_once '../config/Database.php';
| + | $data = getData($apiUrl); |
− | include_once '../objects/Product.php';
| |
| | | |
− | // Dapatkan koneksi database | + | echo "<h2>Daftar User</h2><ul>"; |
− | $database = new Database();
| + | foreach ($data as $user) { |
− | $db = $database->getConnection();
| + | echo "<li>{$user['id']} - {$user['name']}</li>"; |
− | | |
− | // Persiapkan objek produk
| |
− | $product = new Product($db);
| |
− | | |
− | // Dapatkan ID produk yang akan dihapus
| |
− | $data = json_decode(file_get_contents("php://input")); | |
− | | |
− | // Pastikan ID produk tersedia
| |
− | if (!empty($data->id)) {
| |
− | // Set ID produk yang akan dihapus | |
− | $product->id = $data->id;
| |
− | | |
− | // Hapus produk
| |
− | if ($product->delete()) {
| |
− | // Set respons kode 200 - OK
| |
− | http_response_code(200);
| |
− | echo json_encode(array("message" => "Produk berhasil dihapus."));
| |
− | } else {
| |
− | // Set respons kode 503 - Service Unavailable
| |
− | http_response_code(503);
| |
− | echo json_encode(array("message" => "Gagal menghapus produk."));
| |
− | }
| |
− | } else {
| |
− | // Set respons kode 400 - Bad Request
| |
− | http_response_code(400);
| |
− | echo json_encode(array("message" => "ID produk tidak ditemukan."));
| |
| } | | } |
− | ?>
| + | echo "</ul>"; |
| ``` | | ``` |
− |
| |
| | | |
− | **Penjelasan:**
| + | ### 2.2 Jalankan di browser |
| + | - Simpan di `/var/www/html/simple-api/consume.php` |
| + | - Akses di browser: [http://localhost/simple-api/consume.php](http://localhost/simple-api/consume.php) |
| | | |
− | - **Header HTTP:** Menentukan bahwa metode yang diizinkan adalah DELETE dan mengatur tipe konten sebagai JSON. | + | --- |
− | - **Membaca Input:** Mengambil data JSON yang dikirim oleh klien. | |
− | - **Validasi Data:** Memastikan bahwa ID produk disertakan dalam permintaan. | |
− | - **Menghapus Produk:** Memanggil metode `delete()` pada objek produk untuk menghapus data dari database.
| |
| | | |
− | ## 5. Mengonsumsi RESTful API Menggunakan PHP | + | ## 🧪 Bonus: Uji Coba dengan Terminal |
| + | ```bash |
| + | curl http://localhost/simple-api/api.php |
| + | curl http://localhost/simple-api/api.php?id=2 |
| + | ``` |
| | | |
− | Untuk mengonsumsi RESTful API yang telah dibuat, kita dapat menggunakan ekstensi cURL di PHP. Berikut adalah contoh bagaimana melakukan operasi **GET**, **POST**, **PUT**, dan **DELETE** menggunakan cURL.
| + | --- |
| | | |
− | ### 5.1. Konfigurasi cURL | + | ## 📚 Kesimpulan |
− | | + | - Kamu telah berhasil membuat API sederhana menggunakan file JSON. |
− | Buat file `api_client.php` dengan fungsi berikut untuk memanggil API:
| + | - API ini hanya mendukung method `GET`. |
− | | + | - Kamu juga telah belajar cara mengambil data API menggunakan PHP (`curl`). |
− | | |
− | ```php | |
− | <?php
| |
− | function callAPI($method, $url, $data = false) {
| |
− | $curl = curl_init();
| |
− | | |
− | switch (strtoupper($method)) {
| |
− | case "POST":
| |
− | curl_setopt($curl, CURLOPT_POST, 1);
| |
− | if ($data)
| |
− | curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
| |
− | break;
| |
− | case "PUT":
| |
− | curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
| |
− | if ($data)
| |
− | curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
| |
− | break;
| |
− | case "DELETE":
| |
− | curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
| |
− | if ($data)
| |
− | curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
| |
− | break;
| |
− | default: // GET
| |
− | if ($data)
| |
− | $url = sprintf("%s?%s", $url, http_build_query($data));
| |
− | }
| |
| | | |
− | // Opsi umum
| + | --- |
− | curl_setopt($curl, CURLOPT_URL, $url);
| |
− | curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
| |
− | curl_setopt($curl, CURLOPT_HTTPHEADER, array(
| |
− | 'Content-Type: application/json',
| |
− | ));
| |
| | | |
− | $result
| + | Kalau kamu mau versi POST, PUT, DELETE juga, tinggal bilang, nanti kita buatkan lanjutannya ya! Mau dijadikan PDF juga bisa. |
Berikut modul lengkap berjudul **"Membuat dan Mengonsumsi API Sederhana dengan PHP di Ubuntu 24.04"**. Modul ini cocok untuk pemula yang ingin belajar dasar API menggunakan PHP dan dijalankan di Ubuntu 24.04.
---
- 🧩 Modul: Membuat dan Mengonsumsi API Sederhana dengan PHP di Ubuntu 24.04
- 🎯 Tujuan Pembelajaran
- Memahami konsep dasar REST API.
- Membangun API sederhana dengan PHP (tanpa framework).
- Mengonsumsi (mengakses) API menggunakan PHP dan tools seperti `curl`.
- Menjalankan API di server lokal Ubuntu 24.04 (menggunakan Apache).
---
- 🛠️ Persiapan Lingkungan
- 1. Install Apache, PHP, dan cURL
```bash
sudo apt update
sudo apt install apache2 php libapache2-mod-php php-curl
```
- 2. Buat Folder Project
```bash
sudo mkdir -p /var/www/html/simple-api
sudo chown -R $USER:$USER /var/www/html/simple-api
cd /var/www/html/simple-api
```
---
- 📦 Bagian 1: Membuat API Sederhana
- 1.1 Struktur Direktori
```
simple-api/
├── api.php
└── data.json
```
- 1.2 Isi `data.json`
```json
[
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
{"id": 3, "name": "Charlie"}
]
```
- 1.3 Isi `api.php`
```php
<?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents('data.json'), true);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($_GET['id'])) {
$id = intval($_GET['id']);
foreach ($data as $item) {
if ($item['id'] === $id) {
echo json_encode($item);
exit;
}
}
echo json_encode(["error" => "Data not found"]);
} else {
echo json_encode($data);
}
} else {
echo json_encode(["error" => "Method not supported"]);
}
```
- 1.4 Akses API via Browser
- Semua data: [1](http://localhost/simple-api/api.php)
- Data berdasarkan ID: [2](http://localhost/simple-api/api.php?id=2)
---
- 📥 Bagian 2: Mengonsumsi API dengan PHP
- 2.1 File: `consume.php`
```php
<?php
function getData($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$apiUrl = "http://localhost/simple-api/api.php";
$data = getData($apiUrl);
echo "
Daftar User
";
```
- 2.2 Jalankan di browser
- Simpan di `/var/www/html/simple-api/consume.php`
- Akses di browser: [3](http://localhost/simple-api/consume.php)
---
- 🧪 Bonus: Uji Coba dengan Terminal
```bash
curl http://localhost/simple-api/api.php
curl http://localhost/simple-api/api.php?id=2
```
---
- 📚 Kesimpulan
- Kamu telah berhasil membuat API sederhana menggunakan file JSON.
- API ini hanya mendukung method `GET`.
- Kamu juga telah belajar cara mengambil data API menggunakan PHP (`curl`).
---
Kalau kamu mau versi POST, PUT, DELETE juga, tinggal bilang, nanti kita buatkan lanjutannya ya! Mau dijadikan PDF juga bisa.