0
0
FastAPIframework~5 mins

JWT token creation in FastAPI

Choose your learning style9 modes available
Introduction

JWT tokens help keep users logged in safely. They store user info in a secure way so the app knows who you are.

When you want users to log in once and stay logged in while using your app.
When you need to send user info safely between the client and server.
When building APIs that require user authentication.
When you want to avoid storing session info on the server.
When you want a simple way to check if a user is allowed to do something.
Syntax
FastAPI
from datetime import datetime, timedelta
from jose import jwt

SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"

# Function to create a JWT token
# data: dict with user info
# expires_delta: optional expiration time

def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
    to_encode = data.copy()
    expire = datetime.utcnow() + (expires_delta if expires_delta else timedelta(minutes=15))
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

The exp field sets when the token expires.

Use a strong SECRET_KEY to keep tokens safe.

Examples
Creates a token with user ID 'user123' that expires in 15 minutes.
FastAPI
token = create_access_token({"sub": "user123"})
Creates a token that expires in 1 hour instead of 15 minutes.
FastAPI
token = create_access_token({"sub": "user123"}, expires_delta=timedelta(hours=1))
Sample Program

This program creates a JWT token for user 'alice' that expires in 30 minutes and prints it.

FastAPI
from datetime import datetime, timedelta
from jose import jwt

SECRET_KEY = "mysecretkey123"
ALGORITHM = "HS256"

def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
    to_encode = data.copy()
    expire = datetime.utcnow() + (expires_delta if expires_delta else timedelta(minutes=15))
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

# Example usage
if __name__ == "__main__":
    user_data = {"sub": "alice"}
    token = create_access_token(user_data, expires_delta=timedelta(minutes=30))
    print("JWT Token:", token)
OutputSuccess
Important Notes

Keep your SECRET_KEY private and never share it.

Tokens include an expiration time to improve security.

Use the jose library for easy JWT handling in FastAPI.

Summary

JWT tokens store user info safely for authentication.

Create tokens with user data and expiration time.

Use a secret key and a secure algorithm like HS256.