I try to build my own API. I begin so my only model for the moment will be a "User". Here is how I would like to call my API :
HTTP/POST http://example.com/api/user/ # get all the users
HTTP/POST http://example.com/api/user/1 # get the user with id "1"
HTTP/POST http://example.com/api/user/1/delete # delete the user with id "1"
...
So my file routes/web.php
looks like this :
<?php
Route::group(['prefix' => 'api'], function() {
Route::group(['prefix' => 'user'], function() {
Route::post('/', 'ApiController@allUsers');
});
});
?>
But it will not works as I do not pass throught Route::resource
static method, but with regular Route::post
method. So the issue is that VerifyCsrfToken
middleware will trigger and try to check for my CSRF token, but as I want my api to be consume in the future by many other advice I prefer to use my own secure system (which will be a public-private key pairs, but now I just want to check for the integrity of the data I distribute through the api, and I will then set the secure algorithm).
The good news is that Laravel is so clean and let you add your exceptions URL in the VerifyCSRFToken
array which is shaped like this :
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'api/user',
'api/user/{howCanIManageTheWildCard}',
'api/user/{howCanIManageTheWildCard}/delete',
...
];
}
?>
Question :
You see on the middleware above I have 2 issues :
So can I come with a solution wich could let me do a url wildcard like api/*
? Like this it would be so much easier !
You can exclude URLs with /*
Eg.
instead of api/user
you can use api/user/*
read here
Just a suggestion
since you are building an API using laravel you can put all your API routes in api.php
routes file instead of web.php
routes file, In that case you will not have to pass CSRF Token for post request on API routes.
And all the API routes will be like example.com/api/<route>
by default, you will not have to group it.
you can read more about Laravel routing here
happy to help :):):)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With