In this homework exercise, you will build a simple CRUD API using FastAPI and SQLite.
CRUD means:
- Create
- Read
- Update
- Delete
Most database-backed applications use these four actions. For example, a notes app needs to create a note, read notes, edit a note, and delete a note.
We will use a small notes table to keep the example simple.
- How to create rows from an API request.
- How to read rows from SQLite.
- How to update rows.
- How to delete rows.
- How to test non-GET endpoints using FastAPI docs.
- Create a new folder called:
week2-notes-crud
-
Open it in VS Code.
-
Open a new VS Code terminal.
-
Create and activate a virtual environment.
On macOS/Linux:
python3 -m venv .venv
source .venv/bin/activateOn Windows PowerShell:
python -m venv .venv
.venv\Scripts\Activate.ps1- Create
requirements.txt:
fastapi==0.141.1
uvicorn==0.52.4
- Install the requirements.
python -m pip install -r requirements.txt- Create
main.py.
This is a guided example. Read the code, run it, then complete the testing tasks below using your own note content.
| Action | HTTP method and path | Successful response |
|---|---|---|
| Create | POST /notes |
201 and the new note |
| Read all | GET /notes |
200 and a list of notes |
| Read one | GET /notes/{note_id} |
200 and one note |
| Update selected fields | PATCH /notes/{note_id} |
200 and the updated note |
| Delete | DELETE /notes/{note_id} |
200 and a confirmation |
Status codes: 200 means OK, 201 means Created, 404 means Not Found, and 422 means the request failed validation.
BaseModel comes from Pydantic, which FastAPI installs as a dependency. NoteCreate describes the JSON request body: both fields are required strings. NoteUpdate allows a partial update, so either field may be omitted. In this simple example, an omitted field or an explicit null leaves its existing value unchanged.
SQL placeholders (?) pass values separately from the SQL command. This avoids treating user input as SQL. (note_id,) is a tuple containing one value. connection.commit() saves database changes; lastrowid gives the ID of the row just inserted.
- Add this code to
main.py:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from pathlib import Path
import sqlite3
app = FastAPI()
DATABASE_PATH = Path(__file__).resolve().parent / "notes.db"
class NoteCreate(BaseModel):
title: str
text: str
class NoteUpdate(BaseModel):
title: str | None = None
text: str | None = None
def get_connection():
connection = sqlite3.connect(DATABASE_PATH)
connection.row_factory = sqlite3.Row
return connection
def create_table():
connection = get_connection()
cursor = connection.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
text TEXT NOT NULL
)
"""
)
connection.commit()
connection.close()
create_table()
@app.get("/")
def home():
return {"message": "Notes API is running"}
@app.get("/notes")
def get_notes():
connection = get_connection()
cursor = connection.cursor()
cursor.execute("SELECT * FROM notes ORDER BY id")
rows = cursor.fetchall()
connection.close()
return [dict(row) for row in rows]
@app.get("/notes/{note_id}")
def get_note(note_id: int):
connection = get_connection()
cursor = connection.cursor()
cursor.execute("SELECT * FROM notes WHERE id = ?", (note_id,))
row = cursor.fetchone()
connection.close()
if row is None:
raise HTTPException(status_code=404, detail="Note not found")
return dict(row)
@app.post("/notes", status_code=201)
def create_note(note: NoteCreate):
connection = get_connection()
cursor = connection.cursor()
cursor.execute(
"INSERT INTO notes (title, text) VALUES (?, ?)",
(note.title, note.text)
)
connection.commit()
note_id = cursor.lastrowid
connection.close()
return {"id": note_id, "title": note.title, "text": note.text}
@app.patch("/notes/{note_id}")
def update_note(note_id: int, note: NoteUpdate):
connection = get_connection()
cursor = connection.cursor()
cursor.execute("SELECT * FROM notes WHERE id = ?", (note_id,))
existing = cursor.fetchone()
if existing is None:
connection.close()
raise HTTPException(status_code=404, detail="Note not found")
new_title = note.title if note.title is not None else existing["title"]
new_text = note.text if note.text is not None else existing["text"]
cursor.execute(
"UPDATE notes SET title = ?, text = ? WHERE id = ?",
(new_title, new_text, note_id)
)
connection.commit()
connection.close()
return {"id": note_id, "title": new_title, "text": new_text}
@app.delete("/notes/{note_id}")
def delete_note(note_id: int):
connection = get_connection()
cursor = connection.cursor()
cursor.execute("SELECT * FROM notes WHERE id = ?", (note_id,))
existing = cursor.fetchone()
if existing is None:
connection.close()
raise HTTPException(status_code=404, detail="Note not found")
cursor.execute("DELETE FROM notes WHERE id = ?", (note_id,))
connection.commit()
connection.close()
return {"message": "Note deleted"}- Run the app:
uvicorn main:app --reload- Open FastAPI docs:
http://127.0.0.1:8000/docs
- Expand
POST /notesin/docs, click Try it out, replace the example request body with the JSON below, and click Execute:
{
"title": "First note",
"text": "This note is stored in SQLite."
}The response should have status 201 and include the created note's id. Record that ID; use it in all following requests. The app creates notes.db beside main.py on startup, and notes persist between server restarts.
- Open in the browser:
http://127.0.0.1:8000/notes
You should see your note.
-
In
/docs, expandGET /notes/{note_id}, click Try it out, enter the ID returned byPOST, and click Execute. Expect200and that note. -
Test
PATCH /notes/{note_id}with the same ID and this JSON body:
{"title": "Updated first note"}Expect 200. The title changes and the text stays the same. Repeat using your own note content and update only the text field.
-
Stop the server with
Ctrl + C, restart it, and read the note again. Its changes should still be present. -
Test
DELETE /notes/{note_id}with the same ID. Expect200and{"message":"Note deleted"}. Read that ID again; expect404and{"detail":"Note not found"}. -
Choose an ID that is absent from
GET /notes, such as9999. SendPATCH /notes/9999with{"title":"Missing note test"}, thenDELETE /notes/9999; both should return404. SendPOST /noteswith{"title":"Incomplete note"}and no text; expect422, meaning the request body did not match the required model. -
Stop the server with
Ctrl + Cbefore starting Homework 2. If it is already running when you return, use that server rather than starting a second one on port8000.
Before you finish, make sure:
GET /notesreturns notesGET /notes/{note_id}returns one notePOST /notescreates a notePATCH /notes/{note_id}updates a noteDELETE /notes/{note_id}deletes a note- missing notes return a
404error
If PowerShell blocks activation, refer to Week 1's activation instructions. If you see Address already in use, stop the earlier server.
Homework 1 is complete. Continue to Homework 2.