0
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?

Day9 — LaravelでWeb APIを実装する:ルーティング〜JSONレスポンスまでを体験

Last updated at Posted at 2025-12-08

はじめに

Day8 では REST APIの設計思想と正しいURL設計 を学びました。
今日はついにその設計を Laravelで実際に動くAPIとして実装 していきます。

今日のテーマはシンプルです。

「リクエストが来て、JSONでレスポンスを返す」
この流れを Laravelで理解する ことが目標です。

今日のゴール

・API用ルーティングの書き方が分かる

・Controllerでリクエストを受け取れるようになる

・JSONレスポンスを正しく返せるようになる

・Postman で API の動作確認ができる

前提:今回作るAPIの仕様

今回は以下の 最小構成の REST API を作ります。

メソッド URL 処理
GET /api/posts 投稿一覧取得
POST /api/posts 投稿作成

API用ルーティングを定義する

Laravel で API専用ルーティング はここに書きます。

routes/api.php

まずは以下を記述します。

use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;

Route::get('/posts', [PostController::class, 'index']);
Route::post('/posts', [PostController::class, 'store']);

web.php ではなく api.php に書く
✅ 自動で /api プレフィックスが付きます

Controllerを作成する

次に Controller を作ります。

php artisan make:controller PostController

生成されたファイル:

app/Http/Controllers/PostController.php

PostController に index / store を実装

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    // 投稿一覧取得
    public function index()
    {
        $posts = [
            ['id' => 1, 'title' => '最初の投稿'],
            ['id' => 2, 'title' => '2つ目の投稿'],
        ];

        return response()->json([
            'status' => 'success',
            'data' => $posts
        ]);
    }

    // 投稿作成
    public function store(Request $request)
    {
        $title = $request->input('title');

        return response()->json([
            'status' => 'success',
            'message' => '投稿を作成しました',
            'title' => $title
        ], 201);
    }
}

ここで行っていることを整理

処理 意味
$request->input('title') リクエストのデータ取得
response()->json() JSONレスポンスを返す
201 作成成功のステータスコード

Postman で GET 通信テスト

リクエスト

GET http://localhost:8000/api/posts

レスポンス

{
  "status": "success",
  "data": [
    { "id": 1, "title": "最初の投稿" },
    { "id": 2, "title": "2つ目の投稿" }
  ]
}

リクエスト → レスポンスの基本形が完成

Postman で POST 通信テスト

リクエスト設定

Method:POST

URL:http://localhost:8000/api/posts

Body(JSON):

{
  "title": "新しい投稿"
}

レスポンス

{
  "status": "success",
  "message": "投稿を作成しました",
  "title": "新しい投稿"
}

POST通信 + JSONレスポンスも成功

Laravel API 実装の基本構造まとめ

[React]
   ↓ fetch()
[api.php ルーティング]
   ↓
[PostController]
   ↓
[JSONレスポンス]
   ↓
[React]

✅ API開発は この流れだけで完結 します。

よくあるエラーと原因

❌ 404 Not Found

api.php に書いていない

・URL に /api が抜けている

❌ 419 Page Expired

web.php に POST を書いている
 → ✅ API は必ず api.php

❌ JSON が返らない

return response()->json() を使っていない

今日のまとめ

・APIルーティングは routes/api.php

Controller でリクエストを受ける

response()->json() でレスポンスを返す

・GET / POST の API はこれだけで作れる

・Postman で必ず動作確認する

次回 Day10 は…

「React / Next.js から API にリクエストを送る(fetch / axios)」

つまり今日作った Laravel API をフロントから実際に叩きます。

0
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
0
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?