トークンベースの認証により、ステートレスなAPI通信が可能
シンプルなメモアプリのAPI
// routes/api.php
// ユーザー登録
Route::post('/register', function (Request $request) {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = $user->createToken('auth-token')->plainTextToken;
return response()->json([
'token' => $token
]);
});
// ログイン
Route::post('/login', function (Request $request) {
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Unauthorized'], 401);
}
$token = $user->createToken('auth-token')->plainTextToken;
return response()->json([
'token' => $token
]);
});
// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
// メモの作成
Route::post('/memos', function (Request $request) {
$memo = $request->user()->memos()->create([
'title' => $request->title,
'content' => $request->content
]);
return response()->json($memo);
});
// メモの取得
Route::get('/memos', function (Request $request) {
$memos = $request->user()->memos;
return response()->json($memos);
});
});
// ログイン
async function login() {
const response = await fetch('api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'user@example.com',
password: 'password123'
})
});
const data = await response.json();
// トークンを保存
localStorage.setItem('token', data.token);
}
// メモを作成
async function createMemo() {
const response = await fetch('api/memos', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: '新しいメモ',
content: 'メモの内容'
})
});
const memo = await response.json();
console.log('作成されたメモ:', memo);
}