最近では、いろいろなサービスがAPIを提供しています。その中でも、PHPを使って自分のREST APIを作ってみたいと思う方も多いでしょう。本記事では、初学者向けにPHPを使った基本的なREST APIの作り方を説明します。
まずは、REST APIについて簡単に説明します。REST(Representational State Transfer)は、Webサービスを作るためのスタイルの一つです。APIは「Application Programming Interface」の略で、アプリケーション同士が互いにやり取りをするためのルールを指します。REST APIは、HTTPを使って情報をやり取りする、シンプルで使いやすいAPIの形式です。
PHPでREST APIを作成するためには、以下のものが必要です。
ここでは、シンプルな「ユーザー情報」を扱うAPIを作成します。具体的には、ユーザーのデータを取得する、追加する、更新する、削除する機能を持つAPIです。
まず、プロジェクト用のフォルダを作成します。以下のような構成にしましょう。
/api
├─ index.php
└─ users.php
次に、index.phpを作成します。このファイルではリクエストのルーティングを行います。
<?php
header('Content-Type: application/json');
$requestMethod = $_SERVER['REQUEST_METHOD'];
$requestUri = explode('/', $_SERVER['REQUEST_URI']);
if (count($requestUri) > 2 && $requestUri[1] == 'users') {
require 'users.php';
if ($requestMethod == 'GET') {
getUsers();
} elseif ($requestMethod == 'POST') {
createUser();
} elseif ($requestMethod == 'PUT') {
updateUser();
} elseif ($requestMethod == 'DELETE') {
deleteUser();
}
} else {
echo json_encode(['message' => 'Invalid API endpoint']);
}
?>
次に、users.phpで実際の処理を記述します。ここでは、ユーザー情報を管理します。
<?php
$users = [];
// ユーザー情報を取得
function getUsers() {
global $users;
echo json_encode($users);
}
// ユーザーを追加
function createUser() {
global $users;
$input = json_decode(file_get_contents("php://input"), true);
array_push($users, $input);
echo json_encode(['message' => 'User added successfully']);
}
// ユーザーを更新
function updateUser() {
global $users;
$input = json_decode(file_get_contents("php://input"), true);
// 簡単な更新処理の実装
foreach ($users as &$user) {
if ($user['id'] == $input['id']) {
$user = $input;
echo json_encode(['message' => 'User updated successfully']);
return;
}
}
echo json_encode(['message' => 'User not found']);
}
// ユーザーを削除
function deleteUser() {
global $users;
$input = json_decode(file_get_contents("php://input"), true);
foreach ($users as $key => $user) {
if ($user['id'] == $input['id']) {
unset($users[$key]);
echo json_encode(['message' => 'User deleted successfully']);
return;
}
}
echo json_encode(['message' => 'User not found']);
}
?>