I use Dingo with Laravel 5.1 to create simple API.
So at route.php I have:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function($api) {
$api->get('getvoucher', 'App\Http\Controllers\BitemsController@index');
$api->get('update/{key}', 'App\Http\Controllers\BitemsController@update');
$api->post('store', 'App\Http\Controllers\BitemsController@store');
$api->post('authenticate', 'App\Http\Controllers\AuthenticateController@authenticate');
$api->post('logout', 'App\Http\Controllers\AuthenticateController@logout');
$api->get('token', 'App\Http\Controllers\AuthenticateController@getToken');
});
and my BitemsController is:
public function index(Request $request)
{
$bitem = Bitem::where('key',$request->key)->where('id',$request->pin)->first();
return $bitem;
}
public function store(Request $request)
{
$bitem = new Bitem($request->all());
$bitem->save;
return $bitem;
}
Now I use POSTMAN application to test the API, and when I send GET to localhost:8888/api/getvoucher everything is fine, but when I make POST request to store some data then I got error:
"message": "500 Internal Server Error",
"status_code": 500,
"debug": {
"line": 53,
"file": "C:\\wamp\\www\\dine\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken.php",
"class": "Illuminate\\Session\\TokenMismatchException",
"trace": [
To fix the problem I try to add:
protected $except = [
'api/*',
];
inside middleware VerifyCsrfToken.php but wnt work.
Please tell me how to solve my problem...
For Postman to work, you need to either send the correct CSRF header, or remove the need for it on your routes.
I'm assuming based on your screenshot your Dingo API routes are using API_PREFIX=api
in your .env
file.
Check the Laravel documentation on CSRF tokens for more information about those. The gist that @BM2ilabs suggested has some basics on how to find out what CSRF token you're using for local testing in your session to put into Postman.
If you don't want to use CSRF protection, you are correct in using the $except
property on the VerifyCsrfToken
middleware as per the Laravel documentation - this has also come up on Stack Overflow before. Tricky to troubleshoot that without seeing your Kernel
and the full middleware file you're using. If the $except
property really isn't working for you, you can always override the VerifyCsrfToken::handle()
method as per this post and add whatever route checks you like:
public function handle($request, Closure $next)
{
if ( ! $request->is('api/*'))
{
return parent::handle($request, $next);
}
return $next($request);
}
If you are only creating an API that is going to be stateless and not need CSRF protection, you could just comment out the usage of the VerifyCsrfToken
middleware in your Kernel
entirely (and possibly some of the other session middleware), although I would recommend using some kind of authentication/validation that your visitor should be allowed to access the API endpoint.