This Step-by-Step tutorial will guide you through creating a secure password generator using FastAPI, pydantic and uvicorn.
A simple API to generate secure random passwords.
Users can send either:
…and get a generated password based on their preferences.
Why? Working inside a virtual environment keeps dependencies organized.
Open your terminal or command prompt.
Create and navigate to a new directory:
mkdir password-generator-api
cd password-generator-api
Create and activate a virtual environment:
On macOS/Linux:
python3 -m venv .venv
source .venv/bin/activate
On Windows:
python -m venv .venv
.venv\Scripts\activate
Install FastAPI and Uvicorn:
pip install fastapi uvicornInside your project folder, create a file named main.py.
Open main.py in a text editor or IDE.
Add these at the top of main.py:
from fastapi import FastAPI, HTTPException, Query, Body
from pydantic import BaseModel, Field
import string
import secrets
Explanation:
- FastAPI helps create the API.
- HTTPException handles errors.
- Query and Body read inputs from URL or JSON body.
- BaseModel and Field validate JSON input.
- string and secrets generate secure passwords.
Add this below imports:
app = FastAPI()
class PasswordRequest(BaseModel):
length: int = Field(12, ge=4, le=128, description="Password length between 4 and 128")
use_uppercase: bool = True
use_numbers: bool = True
use_special_chars: bool = True
Explanation:
Sets defaults and validation rules for JSON payload.
def generate_password(length: int, use_uppercase: bool, use_numbers: bool, use_special_chars: bool) -> str:
char_pool = string.ascii_lowercase # always include lowercase
if use_uppercase:
char_pool += string.ascii_uppercase
if use_numbers:
char_pool += string.digits
if use_special_chars:
char_pool += string.punctuation
if not char_pool:
raise HTTPException(status_code=400, detail="At least one character type must be selected")
return ''.join(secrets.choice(char_pool) for _ in range(length))
@app.get("/generate-password")
def generate_password_get(
length: int = Query(12, ge=4, le=128, description="Password length"),
use_uppercase: bool = Query(True, description="Include uppercase letters"),
use_numbers: bool = Query(True, description="Include numbers"),
use_special_chars: bool = Query(True, description="Include special characters")
):
password = generate_password(length, use_uppercase, use_numbers, use_special_chars)
return {"password": password}
Explanation:
Users can call this endpoint via browser or HTTP client with URL parameters.
@app.post("/generate-password")
def generate_password_post(payload: PasswordRequest = Body(...)):
password = generate_password(
payload.length, payload.use_uppercase, payload.use_numbers, payload.use_special_chars
)
return {"password": password}
Explanation:
Accepts JSON body input for password generation.
Start the app with:
uvicorn main:app --reload --port 8000
--reload enables auto-reload on code changes (for development). --port specifies the port (default is 8000; change as needed):uvicorn main:app --reload --port 5000
Create run.py:
import uvicorn
import os
if __name__ == "__main__":
port = int(os.getenv("PORT", 5000)) # Read from env or default to 5000
uvicorn.run("main:app", host="127.0.0.1", port=port, reload=True)
Run with:
python run.py
Override port with environment variable:
PORT=8000 python run.py
(For Windows CMD, use set PORT=8000)
Open browser and visit:
http://127.0.0.1:8000/generate-password?length=16&use_uppercase=true&use_numbers=false&use_special_chars=false
You’ll see JSON password output.
Use curl or Postman:
curl -X POST "http://127.0.0.1:8000/generate-password" \
-H "Content-Type: application/json" \
-d '{"length":16, "use_uppercase":true, "use_numbers":false, "use_special_chars":true}'
Visit:
Test endpoints interactively!
Inside your activated environment, run:
pip freeze > requirements.txt
Use later with:
pip install -r requirements.txt
You have created a secure, flexible Password Generator API supporting both GET requests with URL parameters (easy to test in browsers) and POST requests with JSON bodies for more complex interactions.
You learned how to:
requirements.txt