Hello everyone! Welcome back to justlaravel.com, am back with another tutorial. Here I will show you how to consume a Laravel API with passport authentication in Vuejs app. In an earlier post, I have shown you how to integrate passport API into your Laravel apps. As a continuation, I will create a VueJs consumer app here in this tutorial.
You can also watch the video on YouTube here.
Vuejs Consumer App – Create
Let’s create a new Vue standalone app using Vue CLI.
To use Vue CLI, first, we must have it installed in our system. If it is not already installed, just run the following command.
Now let’s create a new Vue app, run the following command.
Click enter for all the default settings to be used for the project. You will see a similar screen as below after creating the app.
Install Axios for making API Calls
As I need to call the API here, I use Axios to do all HTTP requests and handle responses. So let us install it. Run the following command to install Axios.
So after installing it, let us use it in our Vue app.
App.vue file at
src\App.vue import the
axios is ready to use, we can make any HTTP requests through our app now, anyway we are going to call the API which I created earlier here.
VueJs Consumer App – Make API calls
Here am trying accessing data from an API protected with passport. So first I need to register to the API and get the credentials like
client_id and using those credentials I can authenticate the API, get the
access_token and then use that
access_token to get the data I need. See the gif below for registration and obtaining credentials.
So there are 2 API calls here:
- Authenticate the API to get
- Get the data using the
access_tokengenerated in step above.
The API call to get access_token:
In the above snippet, I made a POST call the API to get the access token with parameters
client_secret which I got after registering to the API and also the
password I used when registering to the Laravel API.
then(success) function, I store the access token in a variable and call another function
get_user_data, where I can get the actual data I need.
The API call to get user data:
In the above snippet, to the get the user details a GET call is made to the
users endpoint of the API along with passing access token as an Authorization header to the call.
Now in the
then(success) function, I return the obtained data, which can be displayed onto a page in a way we need.
So let us display the results.
VueJs Consumer App – Display results
For displaying the user details, I will just create a basic HTML table and show the details there. Here I use
v-for directive to loop through the data.
The result looks as below.