Skip to content
The Chat Archive
o4-mini-2025-04-16· OpenAI LMArena Human Preference 140K

Python password endpoint

  1. User

    Python password endpoint

  2. Assistant

    Here’s a self-contained example of a small Python API that lets you

    1. generate a random password
    2. hash a password
    3. verify a password against a hash

    We’ll use FastAPI + Passlib (bcrypt) + Uvicorn.


    1. Install Dependencies

    pip install fastapi uvicorn passlib[bcrypt] python-multipart
    

    2. The Code (main.py)

    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel, Field
    from passlib.context import CryptContext
    import secrets
    import string
    
    app = FastAPI(title="🔐 Password API")
    
    # password‐hashing context
    pwd_ctx = CryptContext(schemes=["bcrypt"], deprecated="auto")
    
    # Pydantic models
    class GenerateRequest(BaseModel):
        length: int = Field(8, ge=4, le=128, description="Desired length of the password")
    
    class HashRequest(BaseModel):
        password: str = Field(..., min_length=1)
    
    class VerifyRequest(BaseModel):
        password: str = Field(..., min_length=1)
        hashed:  str = Field(..., min_length=1)
    
    
    @app.post("/password/generate")
    def generate_password(req: GenerateRequest):
        """Generate a random password of given length."""
        alphabet = string.ascii_letters + string.digits + string.punctuation
        pwd = ''.join(secrets.choice(alphabet) for _ in range(req.length))
        return {"password": pwd}
    
    
    @app.post("/password/hash")
    def hash_password(req: HashRequest):
        """Hash a plaintext password."""
        hashed = pwd_ctx.hash(req.password)
        return {"hashed": hashed}
    
    
    @app.post("/password/verify")
    def verify_password(req: VerifyRequest):
        """Verify a plaintext password against its hash."""
        valid = pwd_ctx.verify(req.password, req.hashed)
        if not valid:
            raise HTTPException(status_code=400, detail="Password does not match hash")
        return {"valid": True}
    

    3. Run the Server

    uvicorn main:app --reload
    

    This will start the server at http://127.0.0.1:8000

    4. Try It Out

    You can use curl or any REST client:

    1. Generate a random password

      curl -X POST "http://127.0.0.1:8000/password/generate" \
        -H "Content-Type: application/json" \
        -d '{"length": 12}'
      

      ➜

      {"password":"A9$dK0p!Zx2Q"}
      
    2. Hash a password

      curl -X POST "http://127.0.0.1:8000/password/hash" \
        -H "Content-Type: application/json" \
        -d '{"password":"mySecret!"}'
      

      ➜

      {"hashed":"$2b$12$...somebcryptsaltandhash..."}
      
    3. Verify a password

      curl -X POST "http://127.0.0.1:8000/password/verify" \
        -H "Content-Type: application/json" \
        -d '{
          "password":"mySecret!",
          "hashed":"$2b$12$...somebcryptsaltandhash..."
        }'
      

      ➜

      {"valid":true}
      

    🎉 That’s it! You now have a tiny password-management API in Python. Let me know if you need:

    • JWT auth integration
    • Password‐reset flows
    • Database persistence
    • Any other tweaks ✨