Fall 2026
  • Discord
  • Gradescope
  • Syllabus

On this page

  • Routes
  • Templates
  • Shared Layouts
  • Forms and Cookies
  • Authentication
  • SQL Injection

Backend Web Development

A website needs a program on the server when visitors can submit information or look up saved data. That program is the backend. We’ll connect Python, HTML, and SQL so a visitor can use our campus calendar through a browser.

Routes

The frontend is the part of a website that runs in the browser. The backend runs on the server. When a browser sends an HTTP request, the server can look up information in a database and send back a response, such as an HTML page, along with a status code.

A route connects a request’s HTTP method and URL path to a Python function. GET asks to retrieve something; POST submits data for processing. The method matters: displaying a form and submitting it can use the same path but different routes. A web framework handles the network communication and calls the appropriate function for us. We will use FastAPI.

Work in a folder containing the SQL reading’s calendar.sql and calendar_create.py. Create and activate its Python environment. Put these dependencies in requirements.txt:

fastapi
uvicorn
jinja2
python-multipart

Install them and create the calendar database:

python -m pip install -r requirements.txt
python calendar_create.py

The route and template examples build one app and share its setup. Keep the imports and app definition as you add routes. Save this first version as webserver.py:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
import uvicorn

app = FastAPI()

@app.get('/', response_class=HTMLResponse)
def home(request: Request):
    return '<h1>CMC Calendar</h1>'

if __name__ == '__main__':
    uvicorn.run('webserver:app', host='127.0.0.1', port=8000, reload=True)

The decorator @app.get('/') attaches home to GET requests for /. HTMLResponse tells the browser to render the returned string as HTML. request: Request asks FastAPI to supply information about the current request.

Run python webserver.py and open http://127.0.0.1:8000. 127.0.0.1 means this computer, and 8000 is the port on which the server listens. Leave that terminal open while visiting the site. Each visit calls home again; reload=True restarts the server when you save changes. In a second terminal, curl can make the same request and print the HTML:

curl http://127.0.0.1:8000/  # <h1>CMC Calendar</h1>

As we develop the app, replace the existing home route rather than adding another route for the same method and path. Keep imports, helpers, and routes above the final if block.

Templates

A template is an HTML file with places to insert data. Our server uses Jinja2 to fill in the template and sends the finished HTML to the browser. To see the result, visit the route that renders the template.

FastAPI uses Jinja2 templates. A context is the dictionary of values available to a template: a key such as events becomes a name the template can use. The template can display a value, repeat a block for each item in a list, or choose a block based on a condition.

The table below shows Jinja2 syntax for inserting values and controlling a page’s layout. (All the cheatsheets from this reading are available as a PDF here.)

Jinja2 syntax Purpose
{ title } Insert the value of title.
{ event['day'] } Look up and insert a field.
{% for event in events %}...{% endfor %} Repeat HTML for each item.
{% if logged_in %}...{% else %}...{% endif %} Choose HTML based on a condition.
{% extends 'base.html' %} Use another template’s layout.
{% block content %}...{% endblock %} Define or fill a named part of the layout.

Create a templates folder beside webserver.py and save this as templates/home.html:

<h2>Upcoming Events</h2>
{% for event in events %}
<article data-event-id="{{ event['id'] }}">
    <h3>{{ event['title'] }}</h3>
    <p>{{ event['venue'] }}:
        <time datetime="{{ event['day'] }}">{{ event['day'] }}</time>
    </p>
</article>
{% endfor %}

The loop repeats one article per event. data-event-id keeps the database ID attached to its article, and datetime gives the date a machine-readable form.

Add the template setup to webserver.py and replace the home route:

from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory='templates')

@app.get('/', response_class=HTMLResponse)
def home(request: Request):
    events = [
        {'id': 1, 'title': 'Ath tea',
         'venue': 'Athenaeum', 'day': '2026-11-12'},
        {'id': 2, 'title': 'W.O.A. reunion',
         'venue': 'Chodosh Social Stairs', 'day': '2026-11-13'},
    ]
    return templates.TemplateResponse(
        request=request, name='home.html', context={'events': events})

The events key in the context matches the name used by the template’s loop. An empty list produces no event articles.

A database query can supply the same context as a list written directly in Python. By default, SQLite returns tuples whose positions follow the columns in SELECT. Setting row_factory to sqlite3.Row also allows field names such as row['title']. A SQL alias names a column in the result without changing the database schema.

Add import sqlite3 to webserver.py. Replace the fixed events list with this query, keeping the TemplateResponse below it:

import sqlite3

connection = sqlite3.connect('calendar.db')
connection.row_factory = sqlite3.Row
events = connection.execute('''
    SELECT events.id, events.title, events.day, venues.name AS venue
    FROM events JOIN venues ON events.venue_id = venues.id
    ORDER BY events.day, events.id
''').fetchall()
connection.close()

For each result, event['venue'] and event[3] retrieve the same value. The template still receives a variable called events with the fields it expects.

HTML escaping preserves text that would otherwise be interpreted as markup. For HTML templates, FastAPI’s Jinja2 setup escapes inserted values automatically. This matters whenever a page displays text supplied by someone else.

If an event’s title is <b>Ath tea</b>, inserting it with { event['title'] } displays those characters instead of making the title bold. Python’s html.escape shows the same conversion:

from html import escape

print(escape('<b>Ath tea</b>'))  # &lt;b&gt;Ath tea&lt;/b&gt;

The FastAPI template guide documents the rendering setup.

Shared Layouts

Most pages on a site share a title, navigation, and styles. Template inheritance puts those common parts in one base template. Each child template fills a named block with its own content. Changing the base then changes all of the pages that use it.

Save this as templates/base.html:

<!doctype html>
<html lang="en">
<head><title>CMC Calendar</title></head>
<body>
    <h1>CMC Calendar</h1>
    <nav><a href="/.">Events</a> <a href="/login">Log in</a></nav>
    {% block content %}{% endblock %}
</body>
</html>

Add these lines around the existing contents of home.html:

{% extends 'base.html' %}
{% block content %}
<!-- Keep the heading and event loop here. -->
{% endblock %}

Rendering home.html now includes the base’s title and menu, with the event list inside its content block. The login page will use the same layout.

Forms and Cookies

To respond to a visitor, the server needs to read data from the request. Query parameters are values in the URL after ?. Form data comes from the named fields in a submitted HTML form. A cookie is a value the browser stores for a site and sends back with later requests. These sources serve different purposes even when they contain the same kind of text.

The table below shows how to read request data, manage cookies, and redirect visitors.

Data or operation FastAPI/Python expression Meaning
Query parameter request.query_params.get('day') Read a value from the URL.
Form field username: str = Form('') Read the submitted field, defaulting to ''.
Cookie request.cookies.get('session') Read a cookie, or None if absent.
Set a cookie response.set_cookie('session', token) Ask the browser to save a value.
Delete a cookie response.delete_cookie('session') Ask the browser to remove it.
Redirect after a POST RedirectResponse('/', status_code=303) Ask the browser to make a GET request for /.

A form’s action gives the destination path, and its method gives the HTTP method. The name of each input becomes the submitted field name. A POST form sends those fields in the request body; a GET form places them in the URL. Passwords belong in the body, where they will not appear in the URL or browser history.

Save this as templates/login.html:

{% extends 'base.html' %}
{% block content %}
<h2>Log In</h2>
{% if bad_credentials %}
<p>That username and password did not match.</p>
{% endif %}
<form action="/login" method="post">
    <label>Username <input name="username"></label>
    <label>Password <input name="password" type="password"></label>
    <button type="submit">Log in</button>
</form>
{% endblock %}

A GET route displays the form:

@app.get('/login', response_class=HTMLResponse)
def login_form(request: Request):
    return templates.TemplateResponse(
        request=request, name='login.html', context={})

Submitting it sends a POST request to /login with fields named username and password. The next section adds the POST route.

A cookie lets a later request refer to an earlier interaction. For example, a login response can set a session cookie and the next visit can return it. Cookies arrive from the browser, so their contents need to be checked rather than accepted as proof of identity. Reading a cookie with .get leaves it in the request’s cookie collection. Setting or deleting a cookie affects the response; the browser applies that change when it receives the response.

Authentication

Authentication checks who a visitor is. A login usually checks a supplied username and password against an account record. Authorization checks what that identified person is allowed to do. Knowing someone’s username does not automatically give them permission to edit every event.

A session connects several requests to the same logged-in visitor. After a successful login, the server creates an unpredictable token and associates it with the account. The browser stores the token in a cookie and sends it with later requests. The server looks up the token to recover the account; an unknown token does not establish a login.

For this local example, add a small organizers table to calendar.db. We’ll give our sample organizer the name Sam, after Sam Altman; the account and password are fictional. Use made-up passwords; deployed applications store password hashes instead of plaintext passwords. Save and run this once as organizers.py:

import sqlite3

connection = sqlite3.connect('calendar.db')
connection.execute('''
    CREATE TABLE IF NOT EXISTS organizers (
        username TEXT PRIMARY KEY,
        password TEXT NOT NULL
    )
''')
connection.execute('INSERT OR IGNORE INTO organizers VALUES (?, ?)',
                   ['Sam', 'sunflower'])
connection.commit()
connection.close()

Add this helper to webserver.py above the routes. The two ? marks receive the username and password as separate values; the next section explains why.

import sqlite3

def are_credentials_good(username, password):
    connection = sqlite3.connect('calendar.db')
    row = connection.execute(
        'SELECT count(*) FROM organizers WHERE username=? AND password=?',
        [username, password]).fetchone()
    connection.close()
    return row[0] > 0

count(*) returns one row containing a count, and row[0] extracts that count. A matching account produces a positive count.

Add the session dictionary and POST route:

from fastapi import Form
from fastapi.responses import RedirectResponse
import secrets

sessions = {}

@app.post('/login', response_class=HTMLResponse)
def login(request: Request, username: str = Form(''),
          password: str = Form('')):
    if not are_credentials_good(username, password):
        return templates.TemplateResponse(
            request=request, name='login.html',
            context={'bad_credentials': True})
    token = secrets.token_urlsafe(32)
    sessions[token] = username
    response = RedirectResponse('/', status_code=303)
    response.set_cookie('session', token, httponly=True, samesite='lax')
    return response

Form('') reads a submitted field, using an empty string if it is missing. A successful response sets the cookie and redirects the browser to / with a GET request. The sequence is POST /login → 303 redirect → GET /. The cookie contains the token, not the password. httponly keeps JavaScript from reading it, and samesite='lax' limits when browsers send it with requests from other sites.

Inside home, after fetching the events, look up the cookie and pass the login state to the template:

token = request.cookies.get('session')
username = sessions.get(token)
return templates.TemplateResponse(
    request=request, name='home.html',
    context={'events': events, 'logged_in': username is not None})

Replace the base template’s navigation with:

<nav>
    <a href="/.">Events</a>
    {% if logged_in %}
    <form action="/logout" method="post">
        <button type="submit">Log out</button>
    </form>
    {% else %}
    <a href="/login">Log in</a>
    {% endif %}
</nav>

The logout route removes the server’s session and asks the browser to remove its cookie:

@app.post('/logout')
def logout(request: Request):
    token = request.cookies.get('session')
    if token in sessions:
        del sessions[token]
    response = RedirectResponse('/', status_code=303)
    response.delete_cookie('session')
    return response

Log in as Sam with sunflower, return to the calendar, and log out. The sessions live in a Python dictionary, so restarting this example server logs everyone out. A deployed app needs shared, persistent session storage and HTTPS. The form guide and cookie guide describe the FastAPI calls.

Hiding a link only changes what the page displays. A visitor can still send a request directly to its URL. A route that changes data must check authorization before making the change. For an event edit, that could mean checking whether the logged-in username is the event’s organizer.

SQL Injection

SQL commands and user input are different kinds of information. The command describes what operation to perform; input supplies values for that operation. SQL injection happens when a program mixes the two, allowing submitted text to change the command’s meaning. It affects reads and writes alike.

Consider this unsafe version of the credential query:

username = 'Sam'
password = "' OR '1'='1"
sql = ("SELECT count(*) FROM organizers WHERE username='" + username
       + "' AND password='" + password + "'")
print(sql)

The resulting command is:

SELECT count(*) FROM organizers
WHERE username='Sam' AND password='' OR '1'='1'

The submitted quote ends the password string, and OR '1'='1' makes the condition true for every row. The account count is positive even though the password is wrong.

A parameterized query sends the command and its input values separately. The ? placeholders mark where values belong, and SQLite treats each supplied value as data. Quotes and SQL keywords inside a parameter remain part of that value. String concatenation, f-strings, and .format all build command text before SQLite receives it; none provides this separation.

After running organizers.py, try the parameterized query in a separate script:

import sqlite3

username = 'Sam'
password = "' OR '1'='1"
connection = sqlite3.connect('calendar.db')
row = connection.execute(
    'SELECT count(*) FROM organizers WHERE username=? AND password=?',
    [username, password]).fetchone()
connection.close()
print(row[0])  # 0

This separate script tests the decision with a real password, a wrong password, and the injection text. It uses the calendar.db created above:

import sqlite3

def are_credentials_good(username, password):
    connection = sqlite3.connect('calendar.db')
    row = connection.execute(
        'SELECT count(*) FROM organizers WHERE username=? AND password=?',
        [username, password]).fetchone()
    connection.close()
    return row[0] > 0

print(are_credentials_good('Sam', 'sunflower'))  # True
print(are_credentials_good('Sam', 'wrong'))  # False
print(are_credentials_good('Sam', "' OR '1'='1"))  # False

The same protection is needed when inserting data. An unsafe insert could turn a submitted title into two rows:

title = "Tea', '2026-11-15'), (2, 'Chess"
sql = "INSERT INTO events (venue_id, title, day) VALUES "
unsafe = sql + "(2, '" + title + "', '2026-11-16')"

Here is the command it constructs:

INSERT INTO events (venue_id, title, day) VALUES
(2, 'Tea', '2026-11-15'), (2, 'Chess', '2026-11-16')

Run this script beside calendar.db. With parameters, that whole submitted title is one field in one new row:

import sqlite3

title = "Tea', '2026-11-15'), (2, 'Chess"

connection = sqlite3.connect('calendar.db')
connection.execute(
    'INSERT INTO events (venue_id, title, day) VALUES (?, ?, ?)',
    [2, title, '2026-11-16'])
connection.commit()
connection.close()

Pass one value per unquoted ?, in order. A quoted '?' is the literal question-mark string, not a placeholder.

Apps that create, read, update, and delete records are called CRUD apps. Those operations use INSERT, SELECT, UPDATE, and DELETE. A transaction groups related changes so they can be saved together with commit or discarded with rollback. For example, reserving a seat and recording its payment should either save both changes or save neither.

The completed local example is webserver.py, with organizers.py and the three templates base.html, home.html, and login.html. Put the HTML files in templates/ beside webserver.py.