birim/laravel-rest-api
Expose Eloquent models as a simple JSON REST API in Laravel. Configure endpoints in a config file, then query /laravel-json/{resource} for lists, skip/take pagination, and basic field search. Optionally control returned attributes via model properties.
Installation
composer require birim/laravel-rest-api
php artisan vendor:publish --provider="Birim\LaravelRestApi\RestApiServiceProvider"
php artisan migrate
config/rest-api.php) and migrations (creates rest_api_tokens table).Basic API Token Setup
php artisan tinker
>>> \Birim\LaravelRestApi\Token::create(['name' => 'My API Client', 'scopes' => ['read']]);
Authorization: Bearer <token>
First API Endpoint
Route::middleware(['auth:api'])->group(function () {
Route::get('/api/data', [DataController::class, 'index']);
});
curl -H "Authorization: Bearer <token>" http://your-app.test/api/data
Scopes for Granular Access
Assign scopes (read, write, admin) during token creation:
Token::create(['name' => 'Admin Dashboard', 'scopes' => ['read', 'write', 'admin']]);
Validate scopes in controllers:
public function update(Request $request) {
if (!$request->user()->tokenCan('write')) {
abort(403);
}
// ...
}
Token Rotation Rotate tokens programmatically:
$token = $user->tokens()->first();
$token->rotate();
Route-Level Protection
Use auth:api middleware for all API routes:
Route::middleware(['auth:api'])->prefix('api')->group(function () {
// Protected routes
});
Controller-Level Validation
Extend BaseController (if provided) or use traits for shared logic:
use Birim\LaravelRestApi\Traits\AuthorizesRequests;
class PostController extends Controller {
use AuthorizesRequests;
public function store(Request $request) {
$this->authorize('create', Post::class);
// ...
}
}
API Rate Limiting Combine with Laravel’s rate limiting:
Route::middleware(['auth:api', 'throttle:60,1'])->group(function () {
// Rate-limited endpoints
});
API Documentation Use tools like Laravel API Docs or Postman to document token-based endpoints.
Event Listeners
Listen for token events (e.g., TokenCreated):
public function handle(TokenCreated $event) {
Log::info("New token created for {$event->token->name}");
}
Token Storage Security
rest_api_tokens table (plaintext by default).HasApiTokens trait with encrypted storage (if extending).
// config/rest-api.php
'encrypt_tokens' => env('REST_API_ENCRYPT_TOKENS', false),
Scope Misconfiguration
tokenCan() consistently:
if (!$request->user()->tokenCan('scope:name')) {
abort(403, 'Insufficient permissions');
}
Middleware Conflicts
auth:api may conflict with other auth middleware (e.g., auth:sanctum).Token Validation Errors
Check the failed_jobs table if tokens aren’t revoked properly.
php artisan queue:work
Logging
Enable debug mode in config/rest-api.php:
'debug' => env('APP_DEBUG', false),
Custom Token Models
Extend the Token model to add fields (e.g., ip_whitelist):
php artisan make:model TokenExtension --extend=Birim\LaravelRestApi\Token
Token Providers Override the default token provider for custom logic:
// app/Providers/AuthServiceProvider.php
public function boot() {
$this->app['auth']->extend('api', function ($app) {
return new CustomTokenProvider();
});
}
API Response Formatting
Use Laravel’s Response macro to standardize API responses:
Response::macro('api', function ($data, $status = 200) {
return response()->json([
'success' => true,
'data' => $data,
], $status);
});
How can I help you explore Laravel packages today?