Laravel REST api

The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object.

Steps to create REST API in laravel

Good source (Update this tutorial)
  1. Add a column to users table named token_key
  2. Go to app\Http\Controllers\Auth\RegisterController.php and inside create function add a column named token_key = str_random(60),
  3. Create a ApiController with –resource for the API
  4. Create Route::group([‘prefix’ => ‘api’, ‘middleware’ => ‘auth:api’], function() {…….})
  5. Now add the api_key in model $fillable and/or hidden
  6. Set business logic in your ApiController.

Passport

Steps:
Run the following commands.
composer require laravel/passport

php artisan migrate

php artisan passport:install
Add the Laravel\Passport\HasApiTokens trait to your App\User model as like below:
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Call the Passport::routes method within the boot method of your AuthServiceProvider as like below:
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport.
Add the CreateFreshApiToken middleware to your web middleware group in your app/Http/Kernel.php file:
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
Run the following commands:
php artisan make:auth
php artisan migrate
To stop checking csrf_token for out api, Go to app\http\middleware\VerifyCsrfToken.php and add the 'api/*' inside $except property as like:
protected $except = [
'api/*'
];
Ok. To get the token for once. Temporarily create a route (web.php) as like below:
Route::get('/token', function(){
     return Auth::user()->createToken('test');
});
Access this /token URL to get token
Now access your desired URL from browser using this token.
Source: https://laravel.com/docs/5.7/passport.
Video source: https://www.youtube.com/watch?v=ogCE2Y_6v34&t=280s
You can create user from command prompt using the following command.
factory('App\User')->create()
Default password will be secret

Without passport using api guard

API Token Authentication in Laravel 5.2 & 5.3
  1. Add an api_token
    The first think you need to do is to add an api_token column to your users table. If you are just starting your application you can likely get away with modifying the user migration that ships with Laravel to include your new column.
  2. add this to your users_table migration
    $table->string('api_token', 60)->unique();
    Note: Be sure to generate and assign an api_token to new users. Something like str_random(60) should be sufficient.
  3. Wrap your routes
    Second, we need to make sure that any routes that will be using Token Authentication are being protected by the auth:api middleware.
    Use the following route group as an example of what your routes might look like.
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/short', 'UrlMapperController@store');
    });
    
    Note: Typically when protecting routes from unauthenticated users, we use the auth middleware, but by appending :api to the end we are telling Laravel that we want to use the driver for the api guard which is set up in the config/auth.php and is defaulted to token.
    At this point, any routes wrapped with your auth:api middleware are only accessible to those that visit the route with a valid api_token in their request.
  4. Getting the User
    To get the authenticated user for this API request, use the following snippet:
    Auth::guard('api')->user();
    
    Just like when we called the middleware, we have to let Laravel know that we want the api guard instead of the default web guard.
  5. Extras
    In the App\Http\Middleware\Authenticate middleware, you might want to change the following lines:
    Update: This has been merged into 5.2. Check out the current Authenticate Middleware here
    // Original
    if ($request->ajax()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }
    // Updated
    if ($request->ajax() || $request->wantsJson()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }
    
    This will return a 401 status code to unauthorized API requests instead of redirect it to a login page.

Labels: ,

© copyright-2020 Rejaul