samedi 14 décembre 2019

Use Laravel API by another (external) Laravel project

I would like to use the API-Routes of my first Laravel instance (I will call this Laravel API provider) by my second instance (I will call this Laravel API client).

The Laravel API provider is based on vue/vuex/vue-router and the API-routes are protected by laravel/passport.

One example for a protected route on the Laravel API provider:

/*Categories Routes*/
Route::group(['prefix' => 'categories'], function ($router) {

    /*Index*/
    Route::middleware('auth:api')->get('/', 'CategoriesApiController@index')
        ->name('api.categories.index');
});

So now I created this call on my Laravel API client:

 $http= new Client();
        $response = $http->request('POST', 'https://laravel-api-provider.local/oauth/token', [
            'headers' => [
                'cache-control' => 'no-cache',
                'Content-Type' => 'application/x-www-form-urlencoded'
            ],
            'form_params' => [
                'client_id' => '2',
                'client_secret' => 'secret',
                'grant_type' => 'password',
                'username' => 'test@example.org',
                'password' => 'password',
            ],
        ]);

        return json_decode((string) $response->getBody(), true);

This returns:

{
  "token_type": "Bearer",
  "expires_in": 31622400,
  "access_token": "eyJ0eXAiOiJKV1QiLC......",
  "refresh_token": "def5020084262c0659e6f916b4da2c33e2a78de2206d......"
}

Seems good. So my next question is: How do I call protected routes (like /api/categories/index) using $response on my Laravel API client?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire