2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

こんにちは!なおです。
2022年、2023年とデフエンジニアの会アドベントカレンダーに参加しています。
前回の記事はこちら

ろう者のエンジニアとして働くということ①
ろう者のエンジニアとして働くということ②
聴こえない人の暮らしに役立つ製品提案

今回は、ちょこっと勉強がてらアプリ開発をしてみたので、それについて書いていきます。
(まだ勉強中なので、間違いあるかも・・)

PHPでAPIを組んでみた

PHPでWebアプリを作っていると、一度は「APIを自分で作りたい」と思う瞬間があります。
とはいえ、フレームワークをがっつり使うほどでもないし、まずは仕組みを理解したい…。
そんなPHP初心者向けに、今回は「自作ミニAPI」をテーマにしてみました。

1. まずAPIって何?

API(Application Programming Interface)は、
「アプリケーション同士が、お互いにデータをやり取りするための窓口」
のようなものです。

日常で使っているサービスの多くも、実はAPIで動いています。

例:
(天気予報アプリ → 天気APIから今日の天気を取得)
(地図サービス → 緯度経度を地図APIに渡して表示)
(SNSアプリ → 投稿をAPIに送信し、一覧もAPIから取得)

今回のミニアプリでも、
「フロントHTMLと「PHPバックエンド」がAPIを使って会話します。

つまり
(フロントがメモを送る → APIが受け取る → JSONに保存)
(APIがメモ一覧を返す → フロントが画面に表示)
という流れです。

APIの仕組みが分かると、
Webアプリの裏側で何が起きているのかが一気にクリアになります。

2. 今回つくるアプリの概要

アプリの役割はシンプルです:

(1)メモをPOSTすると、サーバー側に保存
(2)メモ一覧をGETで取得
(3)フロント側で表示

構成はこんな感じです:

/project-root
 ├ api.php
 ├ MemoStorage.php
 ├ index.html
 └ data.json(自動生成)

データベースは不要で、JSONファイルに保存します。
小規模アプリなら十分実用的ですし、APIの学習にも最適かなと思いました。

3. バックエンド(PHP):ミニAPIを実装する

3-1. データクラス MemoStorage.php

<?php

class MemoStorage {
    private $file;

    public function __construct($file = "data.json") {
        $this->file = $file;

        if (!file_exists($this->file)) {
            file_put_contents($this->file, json_encode([]));
        }
    }

    public function getAll() {
        return json_decode(file_get_contents($this->file), true);
    }

    public function add($text) {
        $memos = $this->getAll();
        $memos[] = [
            "id" => uniqid(),
            "text" => $text,
            "created" => date("Y-m-d H:i:s")
        ];
        file_put_contents($this->file, json_encode($memos, JSON_PRETTY_PRINT));
        return end($memos);
    }
}

3-2. ルーティング処理 api.php

<?php

require_once "MemoStorage.php";

header("Content-Type: application/json");

$storage = new MemoStorage();

$method = $_SERVER["REQUEST_METHOD"];

if ($method === "GET") {
    echo json_encode($storage->getAll());
    exit;
}

if ($method === "POST") {
    $input = json_decode(file_get_contents("php://input"), true);

    if (!isset($input["text"]) || trim($input["text"]) === "") {
        http_response_code(400);
        echo json_encode(["error" => "text is required"]);
        exit;
    }

    $memo = $storage->add($input["text"]);
    echo json_encode($memo);
    exit;
}

http_response_code(405);
echo json_encode(["error" => "Method not allowed"]);

GETとPOSTだけを受け付け、他は405を返すようにしてあります。
APIらしい振る舞いで、学習にも最適です。

4. フロントエンド(index.html):APIを叩いてみる

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>PHPメモアプリ</title>
<style>
body { font-family: sans-serif; padding: 20px; }
#memo-list div { padding: 8px; border-bottom: 1px solid #ddd; }
</style>
</head>
<body>

<h2>メモ入力</h2>
<input id="memo-input" type="text" placeholder="メモを入力">
<button onclick="addMemo()">送信</button>

<h2>メモ一覧</h2>
<div id="memo-list"></div>

<script>
async function loadMemos() {
    const res = await fetch("api.php");
    const memos = await res.json();
    const container = document.getElementById("memo-list");
    container.innerHTML = "";
    memos.forEach(m => {
        const div = document.createElement("div");
        div.textContent = m.created + ": " + m.text;
        container.appendChild(div);
    });
}

async function addMemo() {
    const text = document.getElementById("memo-input").value;
    if (!text.trim()) return;

    await fetch("api.php", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({text})
    });

    document.getElementById("memo-input").value = "";
    loadMemos();
}

loadMemos();
</script>

</body>
</html>

5. 動かし方

(1)上記ファイルを同じフォルダに置く
(2)ローカルサーバー起動:

php -S localhost:8000

(3)ブラウザで

を開けば動作します。

6. まとめ:APIを理解すると開発の自由度が一気に広がる

APIは「データの入り口・出口」を作る技術です。
フロントとバック、他システム同士が会話できるようになることで、
Webアプリの設計もぐっと広がります。

ちょっと色々と説明が足りなかったりするかもしれませんが、よろしくお願いします。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?