Laravelで爆速API開発シリーズ第三弾は「RESTful API」です!
APIの設計の一つであるRESTful APIを採用すると、Laravelでは、ほぼコマンドだけでAPIを作成できてしまいます。
本記事ではRESTFulとは何かについての厳密な説明はいたしませんが、あまり詳しくない人は以下のポイントを押さえておいてください。
- リソース(本記事ではTodo)に着目し、HTTPメソッドは、リソースをどのように操作したいかを表す
- URLはリソースの名前を表す(例: [GET]/todos,[POST]/todos, [PUT]/todos/1, [DELETE]/todos/1)
- APIの処理の結果は、ステータス・コードで表す
作るもの
定番のTodoアプリ
タイトル、完了ステータス、メモを管理します。
使うもの
本シリーズで頻出しているPOSTMAN。
第一弾から読んでくださっている読者様はそろそろ使いこなしてきたのではないでしょうか??
モデルの作成
RESTFulとは操作対象のリソースすなわちLaravelのモデルに着目した設計であるため必然的にモデルの作成から話が始まります。
それでは早速コマンドを叩きましょう。
php artisan make:model Todo -m
マイグレーション定義
Todoが持つカラムはtitle、status、memoの3つです。さきほどモデル作成時に-mオプションをつけたので
database/migrations/に
XXXXXX_create_todos_table.php
が作成されています。
以下のようにしましょう。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTodosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('todos', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('memo')->nullable();
$table->smallInteger('status')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('todos');
}
}
マイグレーションファイルを書き上げたら以下のコマンドを実行してテーブルを作成します。
php artisan migrate
以上でマイグレーション定義は終了です。
コントローラの作成
以下のコマンドを実行しましょう。
php artisan make:controller TodoController --api --model=Todo
これを実行すると、なんということでしょう!
app/Http/Controllers/に
TodoControllerが作成されています。
作成されたTodoController
<?php
namespace App\Http\Controllers;
use App\Todo;
use Illuminate\Http\Request;
class TodoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param \App\Todo $todo
* @return \Illuminate\Http\Response
*/
public function show(Todo $todo)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Todo $todo
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Todo $todo)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Todo $todo
* @return \Illuminate\Http\Response
*/
public function destroy(Todo $todo)
{
//
}
}
中を見ると先ほど定義したモデルがCRUD操作全てのメソッドにタイプヒントされています。すごいですね。。。(感動)
CRUD操作に必要なメソッドはLaravelが自動で作ってくれたのでとりあえずコントローラから離れましょう。
ルートの定義
routes/api.phpに以下の記述をするだけです。
Route::apiResource('todos', 'TodoController');
これにより以下のようなルート定義が自動でなされます。
動詞 | URI | アクション |
---|---|---|
GET | /todos | index |
GET | /todos/{todo} | show |
POST | /todos | store |
PUT | /todos/{todo} | update |
DELETE | /todos/{todo} | destroy |
便利ですね^^
コントローラロジックの構築
app/Http/Controllers/
TodoControllerに戻って以下のようにCRUDロジックを作成しましょう。
<?php
namespace App\Http\Controllers;
use App\Todo;
use Illuminate\Http\Request;
class TodoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return Todo::all();
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$todo = new Todo;
$todo->title = $request->title;
$todo->status = $request->status;
$todo->memo = $request->memo;
$todo->save();
return $todo;
}
/**
* Display the specified resource.
*
* @param \App\Todo $todo
* @return \Illuminate\Http\Response
*/
public function show(Todo $todo)
{
return $todo;
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Todo $todo
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Todo $todo)
{
$todo->title = $request->title;
$todo->status = $request->status;
$todo->memo = $request->memo;
$todo->save();
return $todo;
}
/**
* Remove the specified resource from storage.
*
* @param \App\Todo $todo
* @return \Illuminate\Http\Response
*/
public function destroy(Todo $todo)
{
$todo->delete();
}
}
書き上げたらPOSTMANを開いて例えば以下のようにリクエストしてみましょう。
他にも
[GET] /todos
[GET] /todos/1
[PUT] /todos/1
[DELETE] /todos/1
をリクエストしてみてAPIが正常に動いているか確認してみてください。
これまでの内容でTodoのCRUD操作ができるようになりました。お疲れ様です!
しかし、実際のアプリケーションではそれらの操作を誰にでも許可するわけではありません。
というわけで、Laravelで爆速API開発シリーズ第四弾は「認証と認可」です!
お楽しみに〜

WINDII

最新記事 by WINDII (全て見る)
- Canvaが最高すぎる。使い方を完全ガイド【チュートリアルあり】 - 2019年5月14日
- 人気急上昇中のLaravelをはじめよう!【徹底解説】 - 2019年4月23日
- Laravelの認可を理解して実装してみよう! - 2019年3月29日
この記事へのコメントはありません。