Authentication verifies who the user is.
A common API authentication flow is:
- The user provides an email and password.
- The API verifies the credentials.
- If the credentials are valid, the user is authenticated.
- If the credentials are invalid, the API returns an authentication error.
In FastAPI, HTTPException can be used to return an error when authentication fails.
Code
from fastapi import FastAPI, HTTPException
app = FastAPI()
def authenticate_user(
email: str,
password: str
):
if email != "tarun@example.com":
raise HTTPException(
status_code=401,
detail="Invalid credentials"
)
if password != "123456":
raise HTTPException(
status_code=401,
detail="Invalid credentials"
)
return {
"id": 1,
"email": email
}
Understanding the Code
The authenticate_user() function accepts two values:
def authenticate_user(
email: str,
password: str
):
The email parameter is expected to be a string, and the password parameter is also expected to be a string.
Checking the Email
The email is checked first:
if email != "tarun@example.com":
raise HTTPException(
status_code=401,
detail="Invalid credentials"
)
If the email does not match, FastAPI raises an HTTP exception with status code 401.
Checking the Password
The password is then checked:
if password != "123456":
raise HTTPException(
status_code=401,
detail="Invalid credentials"
)
If the password is incorrect, the API again returns a 401 error.
Returning the User
If both credentials are valid, the function returns the user’s information:
return {
"id": 1,
"email": email
}
Successful Output
When valid credentials are provided, the function returns:
{
"id": 1,
"email": "tarun@example.com"
}
Authentication Flow
User
↓
Email + Password
↓
Authenticate User
↓
Check Email
↓
Check Password
↓
Valid Credentials
↓
Return User
If the credentials are invalid:
Invalid Credentials
↓
HTTPException
↓
Status Code: 401
Summary
Authentication is used to verify the identity of a user.