ChatGPT — OTP Code Generator

Devil’s Advocate
1 min readJan 26, 2023


I asked ChatGPT to come up with a simple Python-based OTP (One Time Password) Code and instantly got this.

from fastapi import FastAPI, HTTPException
import secrets

app = FastAPI()"/generate_otp")
def generate_otp():
otp = secrets.token_hex(3)
return {"otp": otp}"/validate_otp/{otp}")
def validate_otp(otp: str, stored_otp: str = None):
if not stored_otp:
raise HTTPException(status_code=400, detail="OTP not found.")
if otp != stored_otp:
raise HTTPException(status_code=400, detail="Invalid OTP.")
return {"valid": True}

In this example, the /generate_otp endpoint generates a new OTP using the secrets module’s token_hex() function, which generates a random hexadecimal string.

The /validate_otp endpoint takes in the OTP and compares it to the stored OTP.

If the OTP is not found or if the OTP is invalid, the endpoint raises an HTTP exception. If the OTP is valid, the endpoint returns a JSON object with the key “valid” and the value “True”.

Admittedly, this code does not show how to store the generated OTP code in a database. But it certainly does lay the foundation strong enough for a decent programmer to pick it up from there and manage it easily.

Will developers soon become redundant after this revolutionary Codex? I have a feeling we won’t wait longer than 2024 to know the answer.



Devil’s Advocate

Seeker for life. Looking to make technology simpler for everyone.