Building a Vue + FastAPI Application with JWT Authentication

Posted by


In this tutorial, we will walk through the process of building a full-stack web application using Vue.js for the frontend, FastAPI for the backend, and JWT authentication for securing the endpoints.

Step 1: Setting up the Backend with FastAPI

First, let’s set up the backend of our application using FastAPI. FastAPI is a modern web framework for building APIs in Python.

  1. Create a new directory for your project and navigate into it.

  2. Install FastAPI and Uvicorn using pip:
pip install fastapi uvicorn
  1. Create a new Python file for your FastAPI application, for example app.py.

  2. Create a FastAPI application instance:
from fastapi import FastAPI

app = FastAPI()
  1. Define a simple endpoint to test your FastAPI application:
@app.get("/")
async def read_root():
    return {"Hello": "World"}
  1. Run your FastAPI application using Uvicorn:
uvicorn app:app --reload

You can now access your FastAPI application at http://localhost:8000 and see the "Hello, World" message.

Step 2: Setting up the Frontend with Vue.js

Next, let’s set up the frontend of our application using Vue.js. Vue.js is a progressive JavaScript framework for building interactive web interfaces.

  1. Install Vue CLI globally using npm:
npm install -g @vue/cli
  1. Create a new Vue project using Vue CLI:
vue create my-vue-app
  1. Follow the prompts to choose the configuration for your Vue project. You can select the default settings or customize them to fit your needs.

  2. Navigate into the newly created directory for your Vue project:
cd my-vue-app
  1. Run the Vue development server:
npm run serve

You can now access your Vue application at http://localhost:8080 and see the default Vue homepage.

Step 3: Implementing JWT Authentication

Now that we have set up both the backend with FastAPI and the frontend with Vue.js, let’s implement JWT authentication to secure the endpoints of our application.

  1. Install the necessary libraries for JWT authentication in FastAPI:
pip install python-jose pydantic passlib
  1. Create a new Python file for handling authentication, for example auth.py.

  2. Define functions for encoding and decoding JWT tokens in your auth.py file:
from jose import JWTError, jwt
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = "your-secret-key"

ALGORITHM = "HS256"

def create_access_token(data: dict):
    to_encode = data.copy()
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

def verify_token(token: str):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except JWTError:
        return None
  1. Implement authentication endpoints in your FastAPI application to handle login and token verification:
from fastapi import HTTPException, Depends
from .auth import create_access_token, verify_token

@app.post("/login")
async def login(username: str, password: str):
    # Verify credentials and return access token
    # Implement your authentication logic here
    access_token = create_access_token({"sub": username})
    return {"access_token": access_token, "token_type": "bearer"}

async def get_current_user(token: str = Depends(oauth2_scheme)):
    # Verify the token and return the current user
    # Implement your JWT verification logic here
    user = verify_token(token)
    if user is None:
        raise HTTPException(status_code=401, detail="Invalid authentication credentials")
    return user

Step 4: Integrating Backend with Frontend

Finally, let’s integrate the backend with the frontend by making API calls from Vue.js to FastAPI and implementing JWT authentication.

  1. Create a new service file in your Vue project to handle API calls:
import axios from 'axios';

const baseURL = 'http://localhost:8000';

const api = axios.create({
    baseURL,
    headers: {
        'Content-Type': 'application/json'
    }
});

export default {
    login: async (username, password) => {
        const response = await api.post('/login', { username, password });
        return response.data;
    }
}
  1. Use the API service in your Vue components to handle authentication:
<template>
    <div>
        <input type="text" v-model="username" placeholder="Username">
        <input type="password" v-model="password" placeholder="Password">
        <button @click="handleLogin">Login</button>
    </div>
</template>

<script>
import api from './services/api';

export default {
    data() {
        return {
            username: '',
            password: ''
        };
    },
    methods: {
        async handleLogin() {
            try {
                const { access_token } = await api.login(this.username, this.password);
                // Store the token in local storage or Vuex store
            } catch (error) {
                console.error(error);
            }
        }
    }
}
</script>

With these steps, you have successfully built a full-stack web application using Vue.js for the frontend, FastAPI for the backend, and JWT authentication for securing the endpoints. You can further customize and expand the application by adding more features and implementing additional functionality.

0 0 votes
Article Rating

Leave a Reply

17 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sapasflash5442
2 hours ago

Please make more VUE JS + Python Tutorials. Meanwhile, this is exactly what I was looking for my ML App.

@smokus1856
2 hours ago

This tutorial sucks if you have no knowledge of fastAPI

@VietnamShorts
2 hours ago

Very good clip. Thank you. It is fast with not so many details, that let you to do some work by yourself to understand everything. This is a modern CRUD app with very cool stack!

@iUmerFarooq
2 hours ago

Make more Vuejs and Nuxtjs content.
Thank you 💚

@someoneelse3740
2 hours ago

and we put in a bunch of code.. Wow what an explanation. Never had once the impression you understand the code yourself. Copy & Paste is not coding. I wrote multiple FastAPI Endpoints, was looking for frontend introduction. Horrible
Edit: grammar

@zbyszeks3657
2 hours ago

Taking requirements.txt from repository got error on pip install -r requirements.txt

@navaneeth9103
2 hours ago

thats the easy could u provide any repo where protected routes or role based routes are used

@PheakCoding
2 hours ago

I hope you will make another video using Vue + FastApi and mongo-db local🙏

@dimeloloco
2 hours ago

lol FastAPI takes longer to setup than Django. It’s as fast as trying to build an API with Flask lol

@GliGlock
2 hours ago

Don't we need to calculate the hash on the client and pass it to the server?

@paybox4846
2 hours ago

I couldn't find TodoList.vue in repo code, could please help me with this.

@willylukwago6051
2 hours ago

Do you have this tutorial in Node.js & Express version? Please please. I am currently creating my app in Vue js 3 and Node.Js. And I have problems wrapping my head around JWT/VUEX authentication.

@shrimal
2 hours ago

Thanks for a wonderful video on how to setup authentication with fastapi and jwt. Just wondering, what part of the code needs to be updated so we don't have to downgrade to vue@2, vue-router@3? Thanks again.

@Anteater23
2 hours ago

Do you have react JWT video?

@appmake9791
2 hours ago

Excellent. Thank You

@digitalchild
2 hours ago

Is there a reason you aren’t using the new mapped_column() functionality in sqlalchemy 2.0 ?

@cloudcoder01
2 hours ago

Now Svelte : )

17
0
Would love your thoughts, please comment.x
()
x