My Logo

Build a Password Generator API with Python's FastAPI

This Step-by-Step tutorial will guide you through creating a secure password generator using FastAPI, pydantic and uvicorn.

Step-by-Step Tutorial: Build a Password Generator API with FastAPI

What You’ll Build

A simple API to generate secure random passwords.
Users can send either:

…and get a generated password based on their preferences.


Prerequisites


Step 1: Set Up Your Project Environment

Why? Working inside a virtual environment keeps dependencies organized.

  1. Open your terminal or command prompt.

  2. Create and navigate to a new directory:

    mkdir password-generator-api
    cd password-generator-api

  3. Create and activate a virtual environment:

  4. Install FastAPI and Uvicorn:

    pip install fastapi uvicorn

Step 2: Create Your FastAPI Application File

  1. Inside your project folder, create a file named main.py.

  2. Open main.py in a text editor or IDE.


Step 3: Import FastAPI and Required Modules

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.


Step 4: Initialize the FastAPI App

Add this below imports:

app = FastAPI()

Step 5: Define a Pydantic Model for POST Requests

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.


Step 6: Write Helper Function to Generate Passwords

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))

Step 7: Create GET Endpoint with URL Query Parameters

@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.


Step 8: Create POST Endpoint Accepting JSON Payload

@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.


Step 9: Run Your API Server!

Start the app with:

uvicorn main:app --reload --port 8000
uvicorn main:app --reload --port 5000

Optional: Run via Python Script with Custom Port

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)


Step 10: Test Your API

Testing GET Request

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.

Testing POST Request

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}'

Step 11: Explore the Interactive API Docs

Visit:

Test endpoints interactively!


Step 12: Save Your Dependencies for Distribution

Inside your activated environment, run:

pip freeze > requirements.txt

Use later with:

pip install -r requirements.txt

Final Summary

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: