Kembali ke Modul

REST API

Pelajari membuat REST API dengan PHP

15. REST API

Basic REST API
<?php
header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

if ($method == 'GET') {
    $data = [
        'status' => 'success',
        'data' => ['id' => 1, 'name' => 'Budi']
    ];
    echo json_encode($data);
} else if ($method == 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    echo json_encode(['status' => 'created', 'data' => $input]);
}
?>
REST API dengan Routing
<?php
header('Content-Type: application/json');

$request = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];

if (strpos($request, '/api/users') !== false) {
    if ($method == 'GET') {
        // Get all users
        echo json_encode(['users' => []]);
    } else if ($method == 'POST') {
        // Create user
        echo json_encode(['status' => 'created']);
    }
} else if (strpos($request, '/api/posts') !== false) {
    // Handle posts
}
?>
HTTP Status Codes
<?php
header('Content-Type: application/json');

// 200 OK
http_response_code(200);
echo json_encode(['status' => 'success']);

// 201 Created
http_response_code(201);
echo json_encode(['status' => 'created']);

// 400 Bad Request
http_response_code(400);
echo json_encode(['error' => 'Invalid input']);

// 404 Not Found
http_response_code(404);
echo json_encode(['error' => 'Resource not found']);

// 500 Internal Server Error
http_response_code(500);
echo json_encode(['error' => 'Server error']);
?>
Request dengan cURL
<?php
// GET Request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.example.com/users');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$data = json_decode($response, true);
curl_close($curl);

// POST Request
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
?>