FastAPI + Jinja Login Demonstration with Sample Code

Posted by


In this tutorial, we will walk you through how to create a login functionality in a FastAPI app using Jinja templates. We will use FastAPI to create our backend API endpoints and Jinja for creating the frontend HTML templates. By the end of this tutorial, you will have a fully functional login form and authentication system in your FastAPI application.

Step 1: Setting up the Environment
First, let’s create a new directory for our project and set up a virtual environment for it:

$ mkdir fastapi_login_demo
$ cd fastapi_login_demo
$ python3 -m venv venv
$ source venv/bin/activate

Next, install FastAPI and Jinja dependencies using pip:

$ pip install fastapi uvicorn jinja2

Step 2: Create a FastAPI App
In your project directory, create a new Python file named app.py and add the following code:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

Step 3: Create Jinja Templates
Create a new directory named templates in your project directory. Inside this directory, create a new HTML file named index.html and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <h1>Login</h1>
    <form method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"><br><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>

Step 4: Add Login Endpoint
Update your app.py file to include a POST endpoint for handling login requests:

@app.post("/login", response_class=HTMLResponse)
async def login(request: Request, username: str, password: str):
    if username == "admin" and password == "password":
        return templates.TemplateResponse("success.html", {"request": request, "username": username})
    else:
        return templates.TemplateResponse("failure.html", {"request": request})

Step 5: Create Success and Failure Templates
In the templates directory, create two new HTML files named success.html and failure.html:

success.html

<!DOCTYPE html>
<html>
<head>
    <title>Login Success</title>
</head>
<body>
    <h1>Welcome, {{ username }}!</h1>
</body>
</html>

failure.html

<!DOCTYPE html>
<html>
<head>
    <title>Login Failed</title>
</head>
<body>
    <h1>Login failed. Please try again.</h1>
</body>
</html>

Step 6: Run the FastAPI App
You can now run your FastAPI app using uvicorn:

$ uvicorn app:app --reload

Visit http://localhost:8000 in your browser to see the login page. You can test the login functionality by entering the correct username (admin) and password (password) in the form. If successful, you will be redirected to the success page; otherwise, you will see the failure message.

Congratulations! You have successfully implemented a login functionality in FastAPI using Jinja templates. You can further extend this demo by adding user authentication, database integration, and more features to make it a full-fledged login system.

0 0 votes
Article Rating

Leave a Reply

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

where should I keep the token? I am using fastapi and jinja2 templates, and when correctly logging in the site is going to another page (as logged in) but I have no idea what to do with the token. Should I create a global variable "token" in backend or what?

@CreasingDeer
2 hours ago

your web = Server Error (500)

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