15-16 Web Service
15-16 Web Service
WEB SERVICE
Dosen Pengampu
MARDIANTO,S.Kom.,M.Cs
Fakultas Teknologi Informasi
Prodi Ilmu Komputer
// Memproses request
$server->service(file_get_contents("php://input"));
?>
Client SOAP
<?php
require_once("lib/nusoap.php"); // Pastikan NuSOAP diunduh dan tersedia
// URL ke server SOAP
$wsdl = "http://localhost/server.php?wsdl";
// Memeriksa error
$error = $client->getError();
if ($error) {
echo "Constructor error: " . $error;
exit();
}
USE rest_api_example;
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
}
?>
<?php
Reset API
require 'db.php';
// Set header untuk REST API
header("Content-Type: application/json");
$method = $_SERVER['REQUEST_METHOD'];
$conn = getConnection();
// Routing berdasarkan metode HTTP
if ($method == 'GET') {
if (isset($_GET['id'])) {
// Mengambil buku berdasarkan ID
$id = intval($_GET['id']);
$stmt = $conn->prepare("SELECT * FROM books WHERE id = ?");
$stmt->execute([$id]);
$book = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($book);
} else {
// Mengambil semua buku
$stmt = $conn->query("SELECT * FROM books");
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($books);
}
} elseif ($method == 'POST') {
// Menambahkan buku baru
$data = json_decode(file_get_contents("php://input"), true);
$stmt = $conn->prepare("INSERT INTO books (title, author, published_year) VALUES (?, ?, ?)");
$stmt->execute([$data['title'], $data['author'], $data['published_year']]);
echo json_encode(["message" => "Book added successfully", "id" => $conn->lastInsertId()]);
} elseif ($method == 'PUT') {
// Mengupdate buku
$data = json_decode(file_get_contents("php://input"), true);
$stmt = $conn->prepare("UPDATE books SET title = ?, author = ?, published_year = ? WHERE id = ?");
$stmt->execute([$data['title'], $data['author'], $data['published_year'], $data['id']]);
echo json_encode(["message" => "Book updated successfully"]);
} elseif ($method == 'DELETE') {
// Menghapus buku
$id = intval($_GET['id']);
$stmt = $conn->prepare("DELETE FROM books WHERE id = ?");
$stmt->execute([$id]);
echo json_encode(["message" => "Book deleted successfully"]);
} else {
// Metode tidak dikenal
http_response_code(405);
echo json_encode(["message" => "Method not allowed"]);
}
?>