Frontend, Backend and the Model

Updated · 8 min read
hardPython 3.13aiapplicationsfastapipythonarchitecture

This lesson connects the building blocks into a working app. The backend is a small FastAPI web service (pip install fastapi uvicorn) that validates requests, calls the tutor function, and saves every interaction in a SQLite database. The frontend is a single web page that sends questions to the backend and shows the answers.

The Architecture

Three files: page, backend and tutor
FileBlockDescription
index.htmlFrontendIt is used to collect the topic and level and display the answer
app.pyBackend and databaseIt is used to validate requests, call the tutor and store interactions
assistant.pyModel callIt is used to call the model API (from "Building an AI Learning Assistant")

The Backend

app.py
import sqlite3
import time
from pathlib import Path
from typing import Literal
 
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
 
from assistant import Level, explain
 
app = FastAPI(title="AI Learning Assistant")
db = sqlite3.connect("assistant.db", check_same_thread=False)
db.execute("""CREATE TABLE IF NOT EXISTS interactions (
    id INTEGER PRIMARY KEY, student TEXT, topic TEXT, level TEXT, explanation TEXT,
    input_tokens INTEGER, output_tokens INTEGER, seconds REAL, rating INTEGER)""")
 
class Question(BaseModel):
    student: str
    topic: str = Field(min_length=1, max_length=200)
    level: Level = "beginner"
 
class Feedback(BaseModel):
    rating: Literal[1, -1]  # thumbs up or thumbs down
 
@app.get("/", response_class=HTMLResponse)
def page():
    return Path("index.html").read_text()
 
@app.post("/ask")
def ask(question: Question):
    start = time.perf_counter()
    reply, usage = explain(question.topic, question.level)
    seconds = round(time.perf_counter() - start, 2)
    if reply is None:
        raise HTTPException(502, "No answer this time. Please try again.")
    row = db.execute(
        "INSERT INTO interactions (student, topic, level, explanation, input_tokens, output_tokens, seconds) "
        "VALUES (?, ?, ?, ?, ?, ?, ?)",
        (question.student, question.topic, question.level, reply.explanation,
         usage["input_tokens"], usage["output_tokens"], seconds))
    db.commit()
    return {"id": row.lastrowid, **reply.model_dump()}
 
@app.post("/feedback/{interaction_id}")
def feedback(interaction_id: int, body: Feedback):
    row = db.execute("UPDATE interactions SET rating = ? WHERE id = ?", (body.rating, interaction_id))
    db.commit()
    if row.rowcount == 0:
        raise HTTPException(404, "No such answer.")
    return {"saved": True}

Explanation: Question describes a valid request: FastAPI rejects an empty or over-long topic, or an unknown level, before any model call. ask() times the call, stores the answer with its tokens and seconds, and returns the reply as JSON. feedback() saves a thumbs up (1) or down (-1) and returns 404 for an answer that doesn't exist. Database values are passed with ? placeholders, never pasted into the SQL text, which prevents SQL injection.

The Frontend

index.html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>AI Learning Assistant</title>
<style>
  body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
  pre { white-space: pre-wrap; font-family: inherit; background: #f5f7fa; padding: 1rem; border-radius: 8px; }
</style>
<h1>AI Learning Assistant</h1>
<input id="topic" placeholder="What do you want to learn?" maxlength="200">
<select id="level">
  <option>beginner</option><option>intermediate</option><option>advanced</option>
</select>
<button onclick="ask()">Explain</button>
<pre id="answer"></pre>
<script>
  async function ask() {
    const res = await fetch("/ask", {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify({student: "demo", topic: topic.value, level: level.value}),
    });
    const data = await res.json();
    // textContent shows the reply as plain text, so it can never run as code on the page
    answer.textContent = res.ok
      ? `${data.explanation}\n\nExample: ${data.example}\n\nQuiz: ${data.quiz_question}`
      : "Sorry, something went wrong. Please try again.";
  }
</script>
</html>

Explanation: The page sends the topic and level to /ask and shows the reply. It uses textContent, not innerHTML, so even if a reply contained HTML or script, it would appear as plain text and never run. The page contains no key and no prompt; those stay on the server.

Running It

Put the three files in one folder, together with model_api.py from "Calling a Model API", set your three model settings, and start the server:

Terminal
pip install httpx pydantic fastapi uvicorn
export MODEL_API_URL="..." MODEL_API_KEY="..." MODEL_NAME="..."
uvicorn app:app --reload

Then open http://localhost:8000 in a browser. --reload restarts the server whenever you save a file.

Example: Testing the Backend

FastAPI's test client sends requests to the app without a browser. Run this in the same folder, starting without an assistant.db file:

try_app.py
from fastapi.testclient import TestClient
 
from app import app
 
client = TestClient(app)
 
answer = client.post("/ask", json={"student": "advitha", "topic": "photosynthesis", "level": "beginner"})
print(answer.status_code, answer.json()["explanation"])
 
saved = client.post(f"/feedback/{answer.json()['id']}", json={"rating": 1})
print(saved.status_code, saved.json())
 
empty = client.post("/ask", json={"student": "advitha", "topic": "", "level": "beginner"})
print(empty.status_code, empty.json()["detail"][0]["msg"])
 
wrong = client.post("/ask", json={"student": "advitha", "topic": "gravity", "level": "expert"})
print(wrong.status_code, wrong.json()["detail"][0]["msg"])
 
missing = client.post("/feedback/999", json={"rating": 1})
print(missing.status_code, missing.json())

Example output. The status codes, the saved feedback and the error messages are real output of this code. The explanation was produced by an AI model on November 16, 2026; the app ran against a local test server that returned it, not the live API.

Output
200 Plants make their own food using sunlight. Like a kitchen that runs on solar power, leaves take in water and carbon dioxide and use light to turn them into sugar, giving off oxygen.
200 {'saved': True}
422 String should have at least 1 character
422 Input should be 'beginner', 'intermediate' or 'advanced'
404 {'detail': 'No such answer.'}

Explanation: The first request succeeds and is stored as answer 1, and the student's thumbs up is saved against it. The empty topic and the unknown level are rejected with status 422 before the model is called, so bad requests cost nothing. Rating an answer that doesn't exist returns 404.

Going Live for Test Users

NeedWhat to add before real users
Sign-inReal authentication instead of a typed student name, so each person sees only their own history
HTTPS hostingA server or cloud service, with the key in its environment or secrets manager
LimitsA cap on questions per student per hour, to control cost and abuse
MonitoringAlerts on errors and slow answers, and a weekly look at cost and ratings

Common Mistakes

Trusting the student field. It's typed by the page, so anyone can claim to be anyone; real apps need sign-in.

Building SQL by joining strings. Use placeholders, as app.py does.

Showing model output with innerHTML. Use textContent or a framework's safe text rendering.

Interview Corner

How would you structure a simple AI web app?

A frontend that sends requests to a backend; the backend validates them, calls the model with a server-side key, stores the interaction in a database and returns the reply, with sign-in, limits and monitoring before real users arrive.

Why validate requests before calling the model?

Invalid requests should fail fast and free: validation stops bad input, wasted tokens and some kinds of abuse before any model call is made.

Practice

Exercise: a history page. Add GET /history/{student} that returns that student's last five topics and ratings. Test it with the test client, then explain why a real app must check that the person asking is that student.

Check your understanding:

  1. What does FastAPI do with an empty topic?
  2. Why does the page use textContent?
  3. What must change before real users arrive?

Quick check: frontend, backend and the model

4 questions
1What status did an empty topic return?
2Why use ? placeholders in the SQL?
3Why does the page use textContent?
4What replaces the typed student name for real users?

Key Takeaways

Quick reference

NeedCode
Endpoint@app.post("/ask")
ValidationField(min_length=1, max_length=200)
Safe SQLdb.execute("... VALUES (?, ?)", (a, b))
Runuvicorn app:app --reload
TestTestClient(app).post(...)

Was this tutorial helpful?

Lesson 185 of 186