Skip to content

GP5: Backend API

Due: Monday, Nov 30th

In GP1 you wrote use cases: who does what, and what the system shows them. In GP4 you answered your questions in Python. In GP5 you will put both behind a web API: endpoints that serve your GP4 answers and let each kind of user do what your use cases describe. This is the same work you did in HW6, on your own tables, with two additions:

  1. Every request comes from a logged-in person, and your endpoints decide what that person may see and do.
  2. All six teams' endpoints run in one application, with one /docs page, which another team will use to review yours.

Objectives

  • Design REST endpoints for your use cases: resource paths, methods, and status codes.
  • Serve your GP4 queries and views as read endpoints, with response models.
  • Create, update, and delete rows of your own tables, with request models and the errors a client can act on.
  • Decide who may call each endpoint, following the university's policies in the System Description.
  • Document the API well enough that another team can use it from the /docs page alone.

What to commit

In your team's directory, src/planner/<area>/:

  • router.py – your endpoints, at least one read endpoint and one write endpoint per person
  • queries.py – changed as your endpoints need
  • load.py, models.py, and data/ – the items carried over from GP4, described below, and any data your endpoints need to show something
  • schema.dbml and schema.png – updated wherever the tables changed
  • README.md – a new "API" section, described below

To start, one person on the team downloads the template router.py into your team's directory, replaces every <area> with your area, and commits and pushes it; everyone else pulls. Nothing else is needed: src/planner/main.py finds your router.py and adds your endpoints to the application.

Before you start

Run the application

Your gp5 branch is cut on Monday, Nov 16, after the GP4 pull requests and a core update merge. The core update adds the application itself, the login, and a fifth check; the repository's README.md and AGENTS.md describe all three. After you switch to the branch, reinstall and reload, since the core changed:

pip install -e ".[dev]"
python scripts/load.py --drop
fastapi dev src/planner/main.py

Open http://127.0.0.1:8000/docs, click Authorize, and log in as any person in the database, with the password planner. GET /core/me shows who you are and what you may do. Try it as a student, an advisor, and a department admin; you will need all three to test your own endpoints.

Updated versions

The core update also moves pyproject.toml to newer versions of the libraries, the first change since the semester began. Every version is pinned exactly, so that all 24 of us run the same code, and pip install -e ".[dev]" is how your environment follows when the pins change. Run it as above, then check that you have the new versions:

pip list | grep -iE "fastapi|sqlmodel|sqlalchemy|ruff"
Package Was Now What changed
fastapi 0.141.1 0.162.4 Many fixes; a parameter's default value is no longer checked against its type
sqlmodel 0.0.42 0.0.48 A datetime column stores a time zone, and saving one without a time zone is an error
ruff 0.16.8 0.17.4 No longer reports a datetime without a time zone
faker 40.39.0 40.53.0 Fixes for other locales, and small changes to generated dates
psycopg 3.3.5 3.3.8 Bug fixes

SQLAlchemy, which SQLModel is built on, also moves from 2.0 to 2.1.

The SQLModel change is the one you are most likely to see. Saving datetime.now() now fails with "Datetime values must have timezone information"; use datetime.now(UTC), as the core does. Reading a datetime back now gives one with a time zone too, even on SQLite.

Carried over from GP4

Three things the GP3 feedback asked for are due now:

  • Requirements: load the Robotics minor's requirements, so that every Robotics student has requirements to check.
  • Attribute codes: catalog publishes its list of attribute codes in its README, and plans writes those codes, with a credit count, in its placeholders instead of titles such as "Elective".
  • Room types: preferences and scheduling agree on one list of room types and load it on both sides, so that "courses that need a lab" can be checked against the rooms that have one.

Designing the endpoints

Start from your README. Each use case is something a person does, and each thing a person does is a request: list them, then name each one with a method and a path.

Paths are nouns, and the method is the verb, as on the Nov 10 slides. Every path starts with your area, which the router's prefix adds for you; the fifth check fails a path that does not.

Use case Request Who may call it
An advisor lists their advisees GET /advising/advisees an advisor
An advisor sees the quiet students in a catalog year GET /advising/students/quiet?catalog_year=2025 an advisor or an admin
An advisor recommends a course POST /advising/recommendations an advisor
A student accepts or declines a recommendation PATCH /advising/recommendations/{recommendation_id} the student it is for
A student lists their own recommendations GET /advising/recommendations/mine a student

That table is only an example; your team's table goes in your README. Keep it small: a few endpoints that work, and that a reviewer can try, beat many that do not.

Read endpoints

Your GP4 functions are your read endpoints, and the classes you wrote for your views are their response models. An endpoint gets the session and the logged-in person, calls the function, and returns what it returns:

from planner.core import SessionDep
from planner.core.security import CurrentAdvisor

from planner.advising.queries import QuietStudent, quiet_students

router = APIRouter(prefix="/advising", tags=["advising"])


@router.get("/students/quiet")
def read_quiet_students(
    advisor: CurrentAdvisor, session: SessionDep, catalog_year: int
) -> list[QuietStudent]:
    """Active students in one catalog year, fewest logins this term first."""
    return quiet_students(session, catalog_year)

The function's docstring becomes the endpoint's description on /docs, so write it for the person reading that page. A view's parameters that were arguments in GP4 become path parameters, when they name one thing, or query parameters, when they filter.

Write endpoints

A write endpoint changes only your own team's tables, never another team's and never the core's. It follows the pattern from HW6: a request model without table=True, a status code that says what happened, and an IntegrityError turned into a 409.

class RecommendationCreate(SQLModel):
    """What an advisor sends; the advisor is whoever is logged in."""

    student_id: int
    course_id: int
    note: str = Field(min_length=1, max_length=500)


@router.post("/recommendations", status_code=201, responses={409: {"description": "No such student or course"}})
def create_recommendation(
    data: RecommendationCreate, advisor: CurrentAdvisor, session: SessionDep
) -> RecommendationPublic:
    """Recommend a course to a student, who sees it at their next login."""
    recommendation = Recommendation.model_validate(data, update={"advisor_id": advisor.person_id})
    session.add(recommendation)
    try:
        session.commit()
    except IntegrityError:
        session.rollback()
        raise HTTPException(status_code=409, detail="No such student or course") from None
    session.refresh(recommendation)
    return recommendation

RecommendationCreate has no advisor_id. The advisor comes from the login, so no client can recommend in someone else's name, which is the most important line in the example. The responses argument lists the 409 on /docs, which would otherwise show it as Undocumented.

Who may do what

The login is in planner.core.security, and you use it the same way you use SessionDep: declare a parameter, and FastAPI checks it before your function runs.

Parameter type Who gets through Otherwise
CurrentPerson anyone who logs in 401
CurrentStudent a student 403
CurrentEmployee an employee 403
CurrentAdvisor an employee with is_advisor 403
CurrentDirector an employee with is_director 403
CurrentAdmin an employee with is_admin 403

The System Description says who may do what, and your endpoints are where those rules finally hold:

  • A student's records belong to that student. Take the student from the login, as in GET /advising/recommendations/mine, never from a path or query parameter that any student could change. When an endpoint does name a record, check that it belongs to the person asking, and answer 404 if it does not, so that nobody learns which other records exist.
  • Advisors recommend; they do not edit. An advisor may read an advisee's plan and leave a recommendation, but only the student changes the plan, by accepting or declining.
  • Program directors approve substitutions and waivers and assign advisors.
  • Department admins see everything and edit nothing. An endpoint that reads may let admins in too; an endpoint that writes never does.

A rule that takes more than one parameter type, such as "an advisor or an admin," is an if in your function: take CurrentEmployee, and raise a 403 unless one of the flags is set.

Reading other teams' data

Your queries may read any team's tables, as in GP4, and that is how your endpoints use another team's data: a query on their tables, in your queries.py. Do not call another team's endpoints, even though the System Description once allowed it. In one application that would be a request from the server to itself, and it would make your endpoint fail whenever theirs does. Writing to another team's tables is still never allowed.

Checking your work

Run the application and try every endpoint on /docs as three people: one who should get an answer, one who should get a 403, and someone asking for a record that does not exist. Then check the status codes for a request body with a missing field (422) and one that breaks a constraint (409).

Before you open the pull request, run it on PostgreSQL too, with your own schema, as in GP4:

DATABASE_URL=postgresql+psycopg://username@localhost/sec1 python scripts/load.py --drop
DATABASE_URL=postgresql+psycopg://username@localhost/sec1 fastapi dev src/planner/main.py

Every push runs five checks now. The fifth, python scripts/check_api.py, starts the application with every team's router and fails if a path does not start with your area, if two endpoints claim the same method and path, or if any response could include a password_hash.

Updating the README

Add an "API" section after "Queries", with a table of your endpoints: the method and path, who may call it, the use case it serves, and its author. After the table, give a reviewer what they need to try the endpoints: the email addresses of a student, an advisor, and an admin whose data shows something, and the ids of a few records worth looking at.

Grading criteria

I will run your endpoints on /docs and read router.py looking for the following, roughly in order of weight:

  • The endpoints work. Each one returns the right rows, or makes the right change, for the people it is meant for, in both databases.
  • The right people can call them. Every endpoint takes its person from the login, lets in exactly the people your table says, and answers 401, 403, or 404 to everyone else.
  • The status codes and models are right. 201 for a create and 204 for a delete; 404, 409, and 422 where they belong; a request model without the columns a client must not set, and a response model without the columns a client must not see.
  • The endpoints serve your use cases. Each one comes from your README, and together they let each kind of user do what your use cases describe.
  • Every person wrote a read endpoint and a write endpoint, each with its author named and committed by that person.
  • The API documents itself. A reviewer can use it from /docs and your README alone: docstrings, documented error codes, and the test accounts.

I am also looking at the items carried over from GP4, at the commit history, and at how your team responds to the review.

Submission and review

Switch to your <area>/gp5 branch, commit as you go, and open a pull request by the deadline. See the GitHub Workflow for how branches, pull requests, and reviews work, and Code Reviews for what the reviewers are asked to look at. The reviews start in class on Tuesday, Dec 1.