FastAPI Backend Guide

A student's guide to building functional, MySQL-driven APIs with Python.

Environment Setup

Similar to Node.js requiring Npm, FastAPI requires Pip to manage libraries. We will use pymysql for a pain-free database connection.

Terminal
pip install fastapi uvicorn pymysql
Why PyMySQL? Unlike other drivers, PyMySQL is built in pure Python. It avoids "Build Errors" and installation headaches, making it perfect for beginners.

Complete Function-Based Code

This is your entire backend in a single file (main.py). It handles routing, logic, and database connections directly.

main.py
from fastapi import FastAPI, Body
import pymysql

app = FastAPI(docs_url=None, redoc_url=None)

# Database Configuration
db_config = {
    "host": "localhost",
    "user": "YOUR_USERNAME",
    "password": "YOUR_PASSWORD",
    "database": "tpdb",
    "cursorclass": pymysql.cursors.DictCursor
}

def get_db():
    return pymysql.connect(**db_config)

# --- Basic Route ---
@app.get("/hi")
async def hi():
    return {"message": "Hello World"}

# --- Function for Addition ---
@app.post("/add")
async def add(num1: int = Body(...), num2: int = Body(...)):
    return {"addition": num1 + num2}

# --- DB Route: Fetch Employees ---
@app.get("/employees")
async def get_employees():
    conn = get_db()
    with conn.cursor() as cursor:
        cursor.execute("SELECT * FROM employee")
        data = cursor.fetchall()
    conn.close()
    return data

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

Hot Reload (Nodemon Style)

Students familiar with Node.js nodemon will find Python's Hot Reload very intuitive. It restarts the server automatically when you save your file.

Option 1: In the code

Add reload=True inside your uvicorn.run() call.


Option 2: Terminal Command

uvicorn main:app --reload

Testing with Postman

For POST requests like /add, ensure you set the body to raw JSON.

Error 405 Method Not Allowed: This happens if you try to perform a POST on a GET route (or vice-versa). Always check your function decorator!

Data Flow Architecture

Visualizing how the request moves from the client to the database and back.

Postman
Client
(Postman/Browser)
FastAPI
FastAPI
(main.py)
MySQL
MySQL
(tpdb)
Flow Explanation: 1. Client sends a JSON request. 2. FastAPI processes parameters and executes Native SQL. 3. MySQL processes the query. 4. Data is returned as a JSON response.

Summary for Students

FastAPI is high-performance and easy to learn. Key takeaways:

Function-Based

Every route is just a simple Python function decorated with @app.get or @app.post.

Native SQL

You can use standard SQL queries directly for maximum control and performance over your database.

Zero Metadata

Unlike standard FastAPI setups, you can disable the auto-docs to keep your workspace simple and clean, just like Express.