103

In Laravel 5.3 API routes were moved into the api.php file. But how can I call a route in api.php file? I tried to create a route like this:

Route::get('/test',function(){
     return "ok"; 
});

I tried the following URLs but both returned the NotFoundHttpException exception:

  • http://localhost:8080/test/public/test
  • http://localhost:8080/test/public/api/test

How can I call this API route?

Kevin
  • 1,633
  • 1
  • 22
  • 37

2 Answers2

185

You call it by

http://localhost:8080/api/test
                      ^^^

If you look in app/Providers/RouteServiceProvider.php you'd see that by default it sets the api prefix for API routes, which you can change of course if you want to.

protected function mapApiRoutes()
{
    Route::group([
        'middleware' => 'api',
        'namespace' => $this->namespace,
        'prefix' => 'api',
    ], function ($router) {
        require base_path('routes/api.php');
    });
}
peterm
  • 91,357
  • 15
  • 148
  • 157
  • Any idea how to call that in laravel 5.4 ? The default api route: `Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); ` I tried localhost/app/api/user but did not work – utdev Apr 06 '17 at 11:18
  • @utdev You use exactly the same. Remove `app` segment from your URI. It should look along the lines of `localhost/api/user` – peterm Apr 06 '17 at 13:53
2

routes/api.php

Route::get('/test', function () {
    return response('Test API', 200)
                  ->header('Content-Type', 'application/json');
});

Mapping is defined in service provider App\Providers\RouteServiceProvider

protected function mapApiRoutes(){
    Route::group([
        'middleware' => ['api', 'auth:api'],
        'namespace' => $this->namespace,
        'prefix' => 'api',
    ], function ($router) {
        require base_path('routes/api.php');
    });
}