API Rest con Laravel 11
Creación de un API en Laravel 11 usando Sanctum
Build Secure PHP REST API in Laravel with Sanctum Auth
Código en GitHub de REST API in Laravel with Sanctum (usa Laravel 8)
Montaje de ficheros en el VPS:
sshfs usuario@alumno.me:/home/usuario/todo/ servidor -p 22
Conectarse por ssh:
ssh usuario@alumno.me
Situarse en la carpeta del proyecto:
cd ~/todo
Instalar Sanctum, si no se ha configurado la opción api en la creación del proyecto (opciones de instalación en Laravel 11):
php artisan install:api
(php artisan migrate)
Modificar el fichero app/Models/User.php para añadirle use HasApiTokens:
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Fortify\TwoFactorAuthenticatable; use Laravel\Jetstream\HasProfilePhoto; use Laravel\Sanctum\HasApiTokens; use App\Models\Task; class User extends Authenticatable implements MustVerifyEmail { use HasApiTokens; use HasFactory; use HasProfilePhoto; use Notifiable; use TwoFactorAuthenticatable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', 'email_verified_at', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', 'two_factor_recovery_codes', 'two_factor_secret', ]; /** * The accessors to append to the model's array form. * * @var array<int, string> */ protected $appends = [ 'profile_photo_url', ]; /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; } public function tasks() { return $this->hasMany(Task::class); } }
Crear los recursos del API
php artisan make:resource Task
Modificar el fichero
nano app/Http/Resources/Task.php
poner este contenido en el fichero Task.php:
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class Task extends JsonResource { /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->id, 'description' => $this->description, 'created_at' => $this->created_at->format('d/m/Y'), 'updated_at' => $this->updated_at->format('d/m/Y'), ]; } }
Crear los controladores
Crear el fichero app/Http/Controllers/Api/BaseController.php
cd ~/todo mkdir app/Http/Controllers/Api nano app/Http/Controllers/Api/BaseController.php
poner este contenido en el fichero BaseController.php
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use App\Http\Controllers\Controller as Controller; class BaseController extends Controller { /** * success response method. * * @return \Illuminate\Http\Response */ public function sendResponse($result, $message, $code = 200) { $response = [ 'success' => true, 'data' => $result, 'message' => $message, ]; return response()->json($response, $code); } /** * return error response. * * @return \Illuminate\Http\Response */ public function sendError($error, $errorMessages = [], $code = 200) { $response = [ 'success' => false, 'message' => $error, ]; if(!empty($errorMessages)){ $response['info'] = $errorMessages; } return response()->json($response, $code); } }
Crear el fichero app/Http/Controllers/Api/AuthController.php
nano app/Http/Controllers/Api/AuthController.php
poner este contenido en el fichero AuthController.php
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use App\Http\Controllers\Api\BaseController as BaseController; use Illuminate\Support\Facades\Auth; use Validator; use App\Models\User; class AuthController extends BaseController { public function login(Request $request) { if (Auth::attempt(['email' => $request->email, 'password' => $request->password])){ $authUser = Auth::user(); $result['token'] = $authUser->createToken('MyAuthApp')->plainTextToken; $result['name'] = $authUser->name; return $this->sendResponse($result, 'User signed in'); } else { return $this->sendError('Unauthorised.', ['error'=>'incorrect Email/Password']); } } public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'confirm_password' => 'required|same:password', ]); if ($validator->fails()){ return $this->sendError('Error validation', $validator->errors()); } try { $input = $request->all(); $input['password'] = bcrypt($input['password']); $user = User::create($input); $result['token'] = $user->createToken('MyAuthApp')->plainTextToken; $result['name'] = $user->name; return $this->sendResponse($result, 'User created successfully.'); } catch (\Exception $e) { return $this->sendError('Registration Error' , $e->getMessage()); } } public function logout(Request $request) { // Get user who requested the logout $user = request()->user(); //or Auth::user() // Revoke current user token $user->tokens()->where('id', $user->currentAccessToken()->id)->delete(); $success['name'] = $user->name; // return response()->json(['message' => 'User successfully signed out']); return $this->sendResponse($success, 'User successfully signed out.'); } }
TODO:
– validar el email cuando un usuario se registra a través del API
(enviar un email de validación al registrarse, la validación posterior se haría desde el navegador)
API
Using HTTP Methods for RESTful Services
Crear el fichero de rutas routes/api.php
nano routes/api.php
poner este contenido en el fichero api.php:
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\Api\AuthController; use App\Http\Controllers\Api\TasksController; use App\Http\Controllers\Api\MailController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- */ Route::post('login', [AuthController::class, 'login']); Route::post('register', [AuthController::class, 'register']); Route::middleware('auth:sanctum')->group( function () { Route::resource('tasks', TasksController::class); Route::post('logout', [AuthController::class, 'logout']); Route::post('email', [MailController::class, 'sendEmail']); }); Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });
Crear el fichero app/Http/Controllers/Api/TasskController.php y añadir las operaciones CRUD en el API
nano app/Http/Controllers/Api/TasksController.php
poner este contenido en el fichero TasksController.php:
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use App\Http\Controllers\Api\BaseController as BaseController; use Validator; use App\Models\Task; use App\Http\Resources\Task as TaskResource; class TasksController extends BaseController { public function index() { $tasks = Task::where('user_id', auth()->user()->id) ->get(); return $this->sendResponse(TaskResource::collection($tasks), 'Tasks fetched.'); } public function store(Request $request) { $input = $request->all(); $validator = Validator::make($input, [ 'description' => 'required' ]); if ($validator->fails()){ return $this->sendError($validator->errors()); } $task = new Task(); $task->description = $request->description; $task->user_id = auth()->user()->id; $task->save(); return $this->sendResponse(new TaskResource($task), 'Task created.'); } public function show($id) { $task = Task::find($id); if (is_null($task)) { return $this->sendError('Task does not exist.'); } return $this->sendResponse(new TaskResource($task), 'Task fetched.'); } public function update(Request $request, Task $task) { $input = $request->all(); $validator = Validator::make($input, [ 'description' => 'required' ]); if($validator->fails()){ return $this->sendError($validator->errors()); } $task->description = $input['description']; //$task->description = $request->description; $task->save(); return $this->sendResponse(new TaskResource($task), 'Task updated.'); } public function destroy($id) { $task = Task::find($id); if (is_null($task)) { return $this->sendError('Task does not exist.', 'Task NOT deleted.'); } else { $task->delete(); return $this->sendResponse([], 'Task deleted.'); } } }
Crear elcontrolador para enviar emails
nano app/Http/Controllers/Api/MailController.php
poner este contenido en el fichero MailController.php:
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use App\Http\Controllers\Api\BaseController as BaseController; use App\Mail\NewEmail; use Validator; use Exception; class MailController extends BaseController { public function sendEmail(Request $request) { $validator = Validator::make($request->all(), [ 'to' => 'required|email', 'from' => 'required|email', 'subject' => 'required', 'message' => 'required', ]); if ($validator->fails()) { // $status = 501; // return response()->json( ['status' => false, 'message' => $validator->errors()->getMessages()], 501); return $this->sendError('Error validation', $validator->errors()->getMessages(), 400); } else { try { $email = $request->json()->all(); $to = $email['to']; $from = $email['from']; $subject = $email['subject']; $message = $email['message']; $data = [ 'subject' => $subject, 'to' => $to, 'from' => $from, 'message' => $message ]; Mail::send('emails.send', $data, function($message) { $message->to('paco.portada@protonmail.com')->subject('hola'); $message->from('emisor@gmail.com'); }); //Mail::to('paco.portada@protonmail.com')->send(new NewEmail($from, $subject, $message)); // $status = 200; return $this->sendResponse('', 'Email has been sent to ' . $data['to']); } catch (Exception $exception) { // $status = 554; return $this->sendError('', 'Email has not been sent. Error: ' . $exception->getMessage(), 500); } } //return response()->json($message, $status); } }
Crear la carpeta resources/views/emails
cd ~/todo mkdir resources/views/emails
Crear el fichero resources/views/emails/send.blade.php
<!doctype html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0"> <title>Nuevo mensaje</title> </head> <body> <p>Mensaje:</p> <h3>Hola, es un mensaje de prueba</h3> </body> </html>
Duración del token:
How does Laravel sanctum expire tokens?
Configuración en el fichero config/sanctum.php
/* |-------------------------------------------------------------------------- | Expiration Minutes |-------------------------------------------------------------------------- | | This value controls the number of minutes until an issued token will be | considered expired. If this value is null, personal access tokens do | not expire. This won't tweak the lifetime of first-party sessions. | */ //'expiration' => null, //'expiration' => 60 * 24 * 7, 'expiration' => 60,
Código
Más información.
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.