Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 : Api route list

I have the following lines in my routes/api.php

Route::middleware('api')->get('/posts', function (Request $request) {
    Route::resource('posts','ApiControllers\PostsApiController');
});

When I hit http://localhost:8000/api/posts it comes back blank, but when I move the above route to routes/web.php like so:

Route::group(['prefix' => 'api/v1'],function(){
    Route::resource('posts','ApiControllers\PostsApiController');
});

it works.

As a reminder I have cleared the routes cache file with php artisan route:clear and my route list comes with php artisan route:list when my routes/web.php is empty and routes/api.php has the above route:

Domain Method URI Name Action Middleware
GET|HEAD api/posts Closure api

Note that with web routes part the list comes ok and works fine.

What am I doing wrong here?

like image 261
Gammer Avatar asked Apr 23 '17 21:04

Gammer


1 Answers

Dont use the middleware api and see following route example for API routes

Example 1 (in your api.php)

Route::get('test',function(){
    return response([1,2,3,4],200);   
});

visit this route as

localhost/api/test

Example 2 (if you want api authentication, token based auth using laravel passport)

Route::get('user', function (Request $request) {
    ///// controller
})->middleware('auth:api');

You can make get request for this route but you need to pass the access token because auth:api middleware has been used.

Note: see /app/http/kernel.php and you can find the

protected $routeMiddleware = [
//available route middlewares
]

There must not be such (api) kind of middle ware in this file (kernel.php) for routes unless you create one, that why you can not use middleware as api.

Here, How I am creating REST APIs (api.php)

//All routes goes outside of this route group which does not require authentication
Route::get('test',function(){
    return response([1,2,3,4],200);

});
//following Which require authentication ................
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
    Route::get('user-list',"Api\ApiController@getUserList");
    Route::post('send-fax', [
        'uses'=>'api\ApiController@sendFax',
        'as'=>'send-fax'
    ]);
    Route::post('user/change-password', [
        'uses'=>'api\ApiController@changePassword',
        'as'=>'user/change-password'
    ]);

});
like image 166
BetaDev Avatar answered Oct 08 '22 15:10

BetaDev