Create REST API in Laravel with Passport, Rate limiting, Custom Response
Step 1: Installing Laravel App
First, download the Laravel installer using Composer:
composer create-project --prefer-dist laravel/laravel api_learning
if we want to start laravel project in port 8181
php artisan serve --host domain.com --port 8181 &
Step 2: Installing Passport
Step 3: Making First API
First things first we need some data so lets make some migrations.
php artisan make:model Usage -cm --resource
php artisan make:model Article -crmf
php artisan make:model People -mf
As this is a tutorial we don’t want to waste time on the boring stuff so this command creates the model, resource controller (cr
), migration (m
) and factory (f
) all in one go.
Exception Handler
Add this code snippet to app/Exception/Handler.php
public function render($request, Exception $exception){
if ($exception) {
return response()->error("An internal error occured");
}
return parent::render($request, $exception);
}
Hiding Fields in Model
add this code snippet to Model which you created
protected $hidden = array('password', 'token');
Custom Response
Create ResponseMacroServiceProvider.php in Provider folder.
add ResponseServiceMacroApp to config/app.php
‘providers’ => [
App\Providers\ResponseMacroServiceProvider::class,
....
]
Now you can use in your controller
return response()->success(‘test’);
or
return response()->error('test');
Rate Limiting
Customizing the throttle
middleware
We want to limit it to 5 attempts per minute.
Route::group(['prefix' => 'api', 'middleware' => 'throttle:5'], function () {
Route::get('people', function () {
return Person::all();
});
});
And if we want to change it so that, if someone hits the limit, they can’t try again for another 10 minutes?
Route::group(['prefix' => 'api', 'middleware' => 'throttle:5,10'], function () {
Route::get('people', function () {
return Person::all();
});
});
That’s all there is to it!