FastAPI and SQLModel

CS 374, Fall 2026

Where We Are

Deliverable What you built Who could use it
GP3 tables and data anyone with a database client
GP4 queries, as views and Python functions anyone who can run your Python
GP5 endpoints that run those queries anyone with a web browser
  • An API (application programming interface) is how one program asks another program for something
  • A web API takes requests over HTTP, the same protocol your browser uses
    • Today: read-only requests
    • Thursday: create, update, delete

Your Browser Is a Client

http://127.0.0.1:8000/courses?subject=IT&limit=3 typed into the address bar:

One Request, Start to Finish

Anatomy of a Request

  • {course_id} in the decorator's path is filled from the URL, then passed to the function by name
  • Any other parameter of the function comes from the query string, and a default makes it optional

Methods Are Verbs

Method Meaning Usual SQL Success
GET read, and change nothing SELECT 200 OK
POST create a new item in a collection INSERT 201 Created
PATCH change some fields of one item UPDATE 200 OK
PUT replace one item entirely UPDATE 200 OK
DELETE remove one item DELETE 204 No Content
  • The same URL can mean different things: GET /courses/625 vs. DELETE /courses/625
  • A GET must be safe to repeat: browsers, caches, and search engines send them freely
  • Thursday: POST, PATCH, and DELETE

Status Codes Say Who Has a Problem

Code Name When this course uses it
200 OK a GET that worked, even if the list is empty
201 Created a POST that inserted a row
204 No Content a DELETE that worked; there is no body
404 Not Found the path names one item, and it does not exist
409 Conflict the request breaks a constraint, such as a duplicate key
422 Unprocessable Entity a parameter or body has the wrong type or is missing
500 Internal Server Error your code crashed: an unhandled exception

2xx: it worked. 4xx: the client's request was wrong. 5xx: the server is wrong.

Designing URLs: REST

REST (REpresentational State Transfer) is the usual style for web APIs.
URLs name resources with nouns, and the method is the verb:

Instead of Write Why
GET /getCourse?id=625 GET /courses/625 the path names one item
GET /deleteCourse/625 DELETE /courses/625 the method is the verb
GET /coursesFor/CS GET /subjects/CS/courses nesting shows ownership
GET /courses/IT/3 GET /courses?subject=IT&limit=3 filters are optional, so query
  • Plural nouns for collections: /courses, then /courses/{id} for one of them
  • In GP5, every path your team writes starts with your area: /advising/..., /plans/..., etc.

A Path Operation

@app.get("/courses/{course_id}")                                  # 1
def read_course(course_id: int, session: SessionDep) -> Course:   # 2, 3, 4
    course = session.get(Course, course_id)
    if course is None:
        raise HTTPException(status_code=404, detail="Course not found")  # 5
    return course                                                        # 6
  1. Decorator: the method and path this function answers
  2. Path parameter: same name as {course_id}; the type is checked
  3. Dependency: FastAPI supplies the session (next slide)
  4. Return type: decides the shape of the JSON, and the /docs page
  5. Raise to stop with an error status; FastAPI writes the response
  6. Return an object; FastAPI turns it into JSON

Where the Session Comes From

From src/planner/core/db.py, which every team uses:

def get_session() -> Generator[Session, None, None]:
    """Yield one session per request, and close it when the request ends."""
    with Session(engine) as session:
        yield session

SessionDep = Annotated[Session, Depends(get_session)]
  • Depends(get_session) tells FastAPI: call get_session for me; pass in what it yields
  • One session per request; it closes even if your function raises an exception
  • No endpoint ever creates its own engine or session
  • The engine reads DATABASE_URL, so the same code runs on SQLite and PostgreSQL

Validation for Free

GET /courses/abc: the function never ran, and no SQL was sent

  • loc says where the problem is: in the path, at course_id
  • Notice "credits": "3.0" in the earlier response: a Decimal becomes a string in JSON, so no precision is lost

The /docs Page

FastAPI writes it from your decorators, parameters, and return types:

"Try It Out" Feature

  1. Click an endpoint to open
  2. Click Try it out
  3. Fill in the parameters
  4. Click Execute

The page shows the request URL, the status code, and the response body: everything in today's activity

Running Your API

$ fastapi dev practice_api.py

 ⚡️ Starting FastAPI in development mode
 🌐 Server started at http://127.0.0.1:8000
    Documentation at http://127.0.0.1:8000/docs

INFO:     Will watch for changes in these directories: [...]
INFO:     Application startup complete.
INFO:     127.0.0.1:49474 - "GET /courses/625 HTTP/1.1" 200 OK
INFO:     127.0.0.1:49474 - "GET /courses?subject=IT&limit=3 HTTP/1.1" 200 OK
INFO:     127.0.0.1:49474 - "GET /courses/abc HTTP/1.1" 422 Unprocessable Entity
  • dev reloads the server every time you save the file
  • Every request is logged with its status code: the first place to look when something fails
  • Ctrl+C stops the server; only one server can use port 8000 at a time

Your Turn: practice_api.py

  1. Download practice_api.py from today's notes
  2. Set PLANNER_DB to your clone's planner.db
  3. Activate your planner venv, then fastapi dev practice_api.py
  4. Open http://127.0.0.1:8000/docs and try the two examples
  5. Write Problems 1--3; Problem 4 is optional

Each problem lists the URLs to test and what they should return.
Submit to Gradescope at the end of class (or tomorrow).