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.
pip install fastapi uvicorn pymysql
Complete Function-Based Code
This is your entire backend in a single file (main.py). It handles routing, logic, and database connections directly.
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.
- Method: POST
- URL:
http://127.0.0.1:8000/add - Body:
{"num1": 5, "num2": 6}
Data Flow Architecture
Visualizing how the request moves from the client to the database and back.
Client
(Postman/Browser)
FastAPI
(main.py)
MySQL
(tpdb)
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.