FastAPI Login Verification Function

  • Share this:

Code introduction


This code defines a custom FastAPI function that accepts a user object as a parameter and performs login verification through the FastAPI framework. If the username and password are correct, it returns a success message for login, otherwise it returns an HTTP 401 error.


Technology Stack : FastAPI, Pydantic

Code Type : FastAPI custom function

Code Difficulty : Intermediate


                
                    
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
import random

class User(BaseModel):
    email: EmailStr
    password: str

def xxx(user: User):
    app = FastAPI()
    @app.post("/login/")
    def login(user: User):
        if user.email == "admin@example.com" and user.password == "admin":
            return {"message": "Login successful"}
        else:
            raise HTTPException(status_code=401, detail="Invalid credentials")