API Functionality
I am trying to utilize the API feature. I was able to generate a token by using the api/[email protected]&password=password. Once a token is generated, how do I use it in a request? I notice there is already an example APT route called get posts, but if I visit /api/posts then I am redirected back to the dashboard. How does this work? And if I want to create 2 custom endpoints, how do I hit the API using the token ot become authenticated?
Hi,
You can pass the generated token as: -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
.
Get the token from the response and use it in the next request:
curl -k -X POST \
-H "Accept: application/json" \
-d "[email protected]&password=password" \
http://wave.test/api/login
Use the token in the next request:
curl -X GET \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Accept: application/json" \
http://wave3.test/api/posts
You can check out this in the docs here, and there is also an example repository that might help you here.
To add more routes, you should be able to just add them to your API routes as in a standard Laravel app and group them in the 'auth:api' middleware:
OK great thank you. And sorry if this is outside of the scope of Wave support but I have another question. I am making a browser extension that needs to make calls to the API. I can have the user submit a login form in my extension, retrieve a token, and perform some API requests using the token. The next day, the user opens the browser again and needs to do some more API calls. Does the user have to login again? How can I allow the user to stay "logged in" and continue to make API calls? I imagine storing the token on localStorage is not a good idea. Plus, it expires anyway. What's the proper way to do this without logging in every hour? I guess I can use API key, but also dangerous to store locally in the browser since it doesn't expire.
Also, in your link to Line 24, if I change that code to:
// Posts Example API Route
Route::group(['middleware' => 'auth:api'], function (Request $request) {
Route::get('/posts', '\App\Http\Controllers\Api\ApiController@posts');
});
Will the $request
be available in the routes (ApiController@posts)?
Hey there! 👋
You're right—storing the token in localStorage isn't ideal. A better approach is using refresh tokens using the /api/refresh
endpoint, so the user doesn’t need to log in again every session. Alternatively, as mentioned in this thread here, Chrome’s storage API is safer than localStorage.
As for your auth:api
route, yes, I believe that $request
will be available in your controller. You don’t need to pass it in the route definition—Laravel will inject it automatically in your controller method.
Hope this helps!