Skip to main content
This guide will walk you through setting up the Water Quality Backend API and making your first API call. You’ll have a running server and successfully authenticate a user in just a few steps.

Prerequisites

Before you begin, ensure you have:
  • Python 3.9 or higher installed on your system
  • pip package manager
  • Git for cloning the repository
  • A Firebase project (we’ll set this up in the steps below)
New to Python? Download it from python.org

Setup Steps

1

Clone the Repository

Start by cloning the Water Quality Backend repository to your local machine:
git clone <repository-url>
cd water-quality-backend
Verify you’re in the correct directory:
ls -la
You should see files like main.py, requirements.txt, and the app/ directory.
2

Create a Virtual Environment

Create an isolated Python environment to avoid dependency conflicts:
python -m venv .venv
Activate the virtual environment:
source .venv/bin/activate
You’ll know the virtual environment is active when you see (.venv) at the beginning of your terminal prompt.
3

Install Dependencies

Install all required Python packages using pip:
pip install -r requirements.txt
This will install core dependencies including:
  • FastAPI - Web framework
  • Firebase Admin SDK - Firebase integration
  • Pandas, NumPy, Scikit-learn - Data science and ML
  • Socket.IO - Real-time communication
  • PyJWT - JWT token handling
Installation may take 2-3 minutes depending on your internet connection.
4

Configure Environment Variables

Copy the example environment file to create your own configuration:
cp .env.example .env
Open .env in your favorite text editor and configure the following required variables:
.env
# Firebase Configuration (Required)
FIREBASE_API_KEY=your_firebase_api_key
FIREBASE_REALTIME_URL=https://your-project.firebaseio.com

# JWT Secret (Required)
SECRET_KEY=your_secret_key_here

# Firebase Admin SDK Credentials (Required)
FIREBASE_TYPE=service_account
FIREBASE_PROJECT_ID=your_project_id
FIREBASE_PRIVATE_KEY_ID=your_private_key_id
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL=[email protected]
FIREBASE_CLIENT_ID=your_client_id
FIREBASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth
FIREBASE_TOKEN_URI=https://oauth2.googleapis.com/token
FIREBASE_AUTH_PROVIDER_X509_CERT_URL=https://www.googleapis.com/oauth2/v1/certs
FIREBASE_CLIENT_X509_CERT_URL=https://www.googleapis.com/robot/v1/metadata/x509/...
FIREBASE_UNIVERSE_DOMAIN=googleapis.com

Generate a Secret Key

Create a secure secret key for JWT token signing:
python -c 'import secrets; print(secrets.token_hex(32))'
Copy the output and paste it as your SECRET_KEY in the .env file.
Never commit your .env file to version control! It contains sensitive credentials. The .gitignore file is already configured to exclude it.

Optional Services

For full functionality, you can also configure:
.env
# Weather API (Optional)
WEATHER_API_KEY=your_weather_api_key

# Push Notifications (Optional)
ONESIGNAL_APP_ID=your_onesignal_app_id
ONESIGNAL_API_KEY=your_onesignal_api_key

# Email Service (Optional)
RESEND_API_KEY=your_resend_api_key

# AI Analysis (Optional)
OPEN_ROUTER_KEY=your_open_router_key
OPEN_ROUTER_MODEL=openai/gpt-4-turbo

# GitHub OAuth (Optional)
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
GITHUB_CALLBACK_URL=http://localhost:8000/auth/github/callback
FRONTEND_ORIGIN=http://localhost:3000
The API will work with just Firebase and SECRET_KEY configured. Optional services can be added later as needed.
5

Start the Development Server

Launch the FastAPI development server:
fastapi dev app
You should see output similar to:
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process
INFO:     Started server process
INFO:     Waiting for application startup.
INFO:     Application startup complete.
The fastapi dev command enables auto-reload, so the server will automatically restart when you make code changes.

Verify the Server is Running

Open your browser and navigate to:You should see the API response:
{
  "message": "API"
}
6

Make Your First API Call

Now let’s register a new user using the authentication endpoint.

Register a New User

Open a new terminal (keep the server running) and execute:
curl -X POST http://localhost:8000/auth/register/ \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "username": "testuser",
    "password": "SecurePass123!",
    "phone": "+1234567890"
  }'
Expected Response:
{
  "message": "Registered successfully"
}
The password must meet security requirements: at least 8 characters, including uppercase, lowercase, numbers, and special characters.

Login with Your User

Now authenticate and receive a JWT token:
curl -X POST http://localhost:8000/auth/login/ \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "SecurePass123!"
  }'
Expected Response:
{
  "message": "Logged in successfully",
  "user": {
    "uid": "abc123...",
    "email": "[email protected]",
    "username": "testuser",
    "phone": "+1234567890",
    "rol": "user"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Use the Token for Authenticated Requests

Copy the token from the response and use it in subsequent requests:
curl -X GET http://localhost:8000/users/me \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
The JWT token is valid for 30 days and includes user information like uid, email, username, and rol (role).

Alternative: Using the Interactive Docs

FastAPI provides built-in interactive API documentation at http://localhost:8000/docs.

Try the API in Your Browser

  1. Navigate to http://localhost:8000/docs
  2. Find the POST /auth/register/ endpoint
  3. Click “Try it out”
  4. Enter the request body:
    {
      "email": "[email protected]",
      "username": "testuser",
      "password": "SecurePass123!",
      "phone": "+1234567890"
    }
    
  5. Click “Execute”
  6. View the response below
The interactive docs are perfect for exploring the API without needing curl or Postman!

What’s Next?

Congratulations! You’ve successfully:
  • ✅ Set up the Water Quality Backend API
  • ✅ Started the development server
  • ✅ Registered and authenticated a user
  • ✅ Received your first JWT token

Continue Learning

Installation Guide

Learn about production deployment with Docker and advanced configuration

Authentication

Explore all authentication methods including OAuth and password reset

Meter Management

Create and manage water quality meters with real-time data

API Reference

Complete reference for all API endpoints and data models

Troubleshooting

Server Won’t Start

Problem: ModuleNotFoundError or import errors Solution: Make sure your virtual environment is activated and dependencies are installed:
source .venv/bin/activate  # Or Windows equivalent
pip install -r requirements.txt

Firebase Connection Issues

Problem: Firebase authentication or database errors Solution: Verify your Firebase credentials in .env:
  • Check that FIREBASE_PRIVATE_KEY includes the full key with \n for newlines
  • Ensure FIREBASE_PROJECT_ID matches your Firebase console
  • Verify the Realtime Database URL is correct

Registration Fails

Problem: User registration returns validation errors Solution: Check password requirements:
  • Minimum 8 characters
  • At least one uppercase letter
  • At least one lowercase letter
  • At least one number
  • At least one special character
If you see SKIP_FIREBASE_INIT errors, make sure this environment variable is not set in your .env file.

Need Help?

  • Interactive Docs: http://localhost:8000/docs
  • Postman Collection: Check the .postman/ directory for pre-configured requests
  • Example Tests: See /tests directory for working code examples

Build docs developers (and LLMs) love