CoolFace
Apppublic

civic29/formsetu-backend

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes
App README

A FastAPI-based backend service for FormSetu - an AI-powered government form assistant application.

Tech Stack

  • Framework: FastAPI (Python)
  • Database: PostgreSQL
  • ORM: SQLAlchemy
  • Authentication: JWT (JSON Web Tokens)
  • Password Hashing: bcrypt (via passlib)

Project Structure

src/engine/
├── app/
│   ├── api/
│   │   ├── __init__.py
│   │   ├── auth.py          # Authentication routes (signup, login, me)
│   │   └── routes.py        # Main API router
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py        # Application settings
│   │   ├── deps.py          # Dependency injection (DB session, auth)
│   │   └── security.py      # Password hashing & JWT utilities
│   ├── db/
│   │   ├── __init__.py
│   │   ├── base.py          # SQLAlchemy Base
│   │   └── session.py       # Database session configuration
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py          # User database model
│   ├── schemas/
│   │   ├── __init__.py
│   │   └── user.py          # Pydantic schemas for request/response
│   └── main.py              # Application entry point
├── .env                     # Environment variables (create this)
├── requirements.txt         # Python dependencies
└── README.md               # This file

Prerequisites

  1. 1.Python 3.10+ installed
  2. 2.PostgreSQL installed and running
  3. 3.pip package manager

Setup Instructions

1. Create PostgreSQL Database

Open pgAdmin or use command line:

sql
CREATE DATABASE formsetu;

Or via command line (Windows):

powershell
$env:PGPASSWORD = "your_password"
& "C:\Program Files\PostgreSQL\18\bin\psql.exe" -U postgres -c "CREATE DATABASE formsetu;"

2. Create Virtual Environment (Optional but Recommended)

bash
# From project root
python -m venv .venv

# Activate (Windows PowerShell)
.\.venv\Scripts\Activate.ps1

# Activate (Linux/Mac)
source .venv/bin/activate

3. Install Dependencies

bash
cd src/engine
pip install -r requirements.txt

4. Configure Environment Variables

Create a .env file in src/engine/:

env
# Database Configuration
DATABASE_URL=postgresql://postgres:admin@localhost:5432/formsetu

# JWT Configuration
SECRET_KEY=your-super-secret-key-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=10080

# Environment
ENVIRONMENT=dev
PROJECT_NAME=FormSetu API
Note: Change admin to your PostgreSQL password and generate a secure SECRET_KEY for production.

5. Run the Server

bash
cd src/engine
uvicorn app.main:app --reload --port 8000

The API will be available at: http://localhost:8000

API Documentation

Once the server is running, access the interactive API docs:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

API Endpoints

Health Check

EndpointMethodDescription
/GETRoot endpoint - check if server is running
/api/healthGETHealth check endpoint

Authentication

EndpointMethodDescriptionAuth Required
/api/auth/signupPOSTRegister a new userNo
/api/auth/loginPOSTAuthenticate and get tokenNo
/api/auth/meGETGet current user profileYes

Request/Response Examples

Signup

Request:

json
POST /api/auth/signup
{
  "email": "user@example.com",
  "password": "securepassword",
  "name": "John Doe",
  "phone": "9876543210"  // optional
}

Response (201 Created):

json
{
  "user": {
    "id": 1,
    "email": "user@example.com",
    "name": "John Doe",
    "phone": "9876543210",
    "is_active": true,
    "created_at": "2024-01-15T10:30:00"
  },
  "token": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "bearer"
  },
  "message": "Account created successfully"
}
Login

Request:

json
POST /api/auth/login
{
  "email": "user@example.com",
  "password": "securepassword"
}

Response (200 OK):

json
{
  "user": {
    "id": 1,
    "email": "user@example.com",
    "name": "John Doe",
    "phone": "9876543210",
    "is_active": true,
    "created_at": "2024-01-15T10:30:00"
  },
  "token": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "bearer"
  },
  "message": "Login successful"
}
Get Current User

Request:

GET /api/auth/me
Authorization: Bearer <access_token>

Response (200 OK):

json
{
  "id": 1,
  "email": "user@example.com",
  "name": "John Doe",
  "phone": "9876543210",
  "is_active": true,
  "created_at": "2024-01-15T10:30:00"
}

Authentication Flow

┌─────────────────────────────────────────────────────────────┐
│                    Authentication Flow                       │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  1. SIGNUP                                                   │
│     ┌──────────┐    POST /signup    ┌──────────┐            │
│     │  Client  │ ─────────────────> │  Server  │            │
│     │          │ <───────────────── │          │            │
│     └──────────┘   JWT + User Data  └──────────┘            │
│                                                              │
│  2. LOGIN                                                    │
│     ┌──────────┐    POST /login     ┌──────────┐            │
│     │  Client  │ ─────────────────> │  Server  │            │
│     │          │ <───────────────── │          │            │
│     └──────────┘   JWT + User Data  └──────────┘            │
│                                                              │
│  3. AUTHENTICATED REQUESTS                                   │
│     ┌──────────┐   GET /me + JWT    ┌──────────┐            │
│     │  Client  │ ─────────────────> │  Server  │            │
│     │          │ <───────────────── │          │            │
│     └──────────┘     User Data      └──────────┘            │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Database Schema

Users Table

ColumnTypeConstraints
idINTEGERPRIMARY KEY, AUTO INCREMENT
emailVARCHAR(255)UNIQUE, NOT NULL, INDEXED
hashed_passwordVARCHAR(255)NOT NULL
nameVARCHAR(255)NOT NULL
phoneVARCHAR(20)NULLABLE
is_activeBOOLEANDEFAULT TRUE
created_atDATETIMEDEFAULT NOW
updated_atDATETIMEDEFAULT NOW, ON UPDATE NOW

Security Features

  1. 1.Password Hashing: Passwords are hashed using bcrypt before storage
  2. 2.JWT Tokens: Stateless authentication with configurable expiration
  3. 3.CORS Protection: Configured for allowed frontend origins
  4. 4.Input Validation: Pydantic schemas validate all input data
  5. 5.Email Validation: Email format is validated on signup

Error Handling

Status CodeDescription
400Bad Request - Invalid input data
401Unauthorized - Invalid credentials or expired token
403Forbidden - Account inactive
404Not Found - Resource doesn't exist
422Unprocessable Entity - Validation error
500Internal Server Error

Development

Running in Development Mode

bash
uvicorn app.main:app --reload --port 8000

The --reload flag enables auto-reload on code changes.

Testing with cURL/PowerShell

powershell
# Test signup
Invoke-RestMethod -Uri "http://localhost:8000/api/auth/signup" `
  -Method POST -ContentType "application/json" `
  -Body '{"email":"test@example.com","password":"test123","name":"Test User"}'

# Test login
Invoke-RestMethod -Uri "http://localhost:8000/api/auth/login" `
  -Method POST -ContentType "application/json" `
  -Body '{"email":"test@example.com","password":"test123"}'

Troubleshooting

Common Issues

  1. 1.Database Connection Error
  2. 2.Ensure PostgreSQL is running
  3. 3.Check DATABASE_URL in .env file
  4. 4.Verify database exists: \l in psql
  1. 1.CORS Errors
  2. 2.Frontend origin must be in allowed origins list
  3. 3.Check main.py for CORS configuration
  1. 1.Invalid Token
  2. 2.Token may be expired (default: 7 days)
  3. 3.Ensure token is sent in Authorization header as Bearer <token>
  1. 1.Module Not Found
  2. 2.Ensure virtual environment is activated
  3. 3.Run pip install -r requirements.txt

Production Deployment

For production, ensure:

  1. 1.Use a strong, unique SECRET_KEY
  2. 2.Set ENVIRONMENT=production
  3. 3.Use HTTPS
  4. 4.Configure proper CORS origins
  5. 5.Use environment variables (not .env file)
  6. 6.Set up proper logging
  7. 7.Use a process manager (gunicorn, supervisor)
bash
# Production run example
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000