Exercise: Pet Adoption Applications

Finish an adoption center's FastAPI applications router with a request model whose field rules refuse bad applications with a 422 and a response model that keeps the staff's private notes out of every answer, and let TestClient's tests check each one.

Journeyman · FastAPI · Python · Updated

By

The Happy Tails Adoption Center's API takes whatever it's sent: an application with an empty name, from a 12-year-old, for a pet the center doesn't have. And when an applicant looks up their application, the API sends back the staff's private notes about them too. You'll fix both with two Pydantic models, the way this chapter built them: one with the rules every application must follow, and one that chooses exactly what goes back out. Tests check every answer as you go.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-pet-adoption-applications, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:

cd ~/python-course
git clone https://github.com/ask-codey/exercise-fastapi-pet-adoption-applications.git

Git makes a folder, exercise-fastapi-pet-adoption-applications, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):

python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt

On a Mac (zsh):

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

The prompt starts with (.venv) once the virtual environment is on. The exercise's README says what each command does, and what to do if PowerShell won't run the second one.

The folder holds:

  • routers/applications.py: the applications router, for you to finish.
  • main.py: makes the app and adds the applications router with app.include_router. Ready to use.
  • data.py: the center's three applications, in the list APPLICATIONS, each with a status and private staff_notes, and reset_applications(), which the tests use to put the applications back before each test.
  • tests/test_applications.py: the tests, which send requests to your app with TestClient. You don't need to change it.
  • requirements.txt and pytest.ini: the packages the app and the tests need, at exact versions, and where pytest finds the tests and your code.

What to do

routers/applications.py imports what you need and makes router, with the prefix /applications and the tag applications, and no routes yet, so for now every request answers 404. The comment at its top lists the rules and every request the API should answer:

ApplicationIn, the body of POST /applications, and its rules:
  name       text of 1 to 80 characters                 email      a valid email address
  age        a whole number, 18 or over                 pet_name   text of 1 to 40 characters
  pet_type   "dog", "cat" or "rabbit", exactly          has_yard   true or false; false when it isn't sent

ApplicationOut, every answer: id, name, email, age, pet_name, pet_type, has_yard and status. Never staff_notes.

POST /applications                   201, the new application as an ApplicationOut, kept in APPLICATIONS. For the body
                                     {"name": "Sam", "email": "sam@example.com", "age": 29, "pet_name": "Juniper",
                                      "pet_type": "cat", "has_yard": false}
                                     the answer is {"id": 4, "name": "Sam", "email": "sam@example.com", "age": 29,
                                     "pet_name": "Juniper", "pet_type": "cat", "has_yard": false, "status": "received"}:
                                     its id is one more than the number of applications, its status is always
                                     "received", and it's kept with "staff_notes": "" (empty)
POST /applications, a broken rule    422, FastAPI's own answer, with an entry whose loc names the field, such as
                                     ["body", "age"] for an age of 17
POST /applications, with "status"    201, as above: the body can't set status or staff_notes, so the status is
or "staff_notes" in the body         "received" and the notes are kept empty
GET /applications/1                  200, application 1 as an ApplicationOut, with no staff_notes
GET /applications/99                 404, {"detail": "There's no application 99."}
GET /applications/abc                422, FastAPI's own answer: an application's id is a whole number

The docs page shows ApplicationIn as the body of POST /applications, and ApplicationOut as the answer of both routes.

  1. Write ApplicationIn, the model for what comes in, with every rule above on its field.
  2. Write ApplicationOut, the model for what goes out: eight fields, and no staff_notes.
  3. Take applications in with POST /applications: build the application to keep from the model, with its id, "status": "received" and "staff_notes": "", add it to APPLICATIONS, and answer 201 with it as an ApplicationOut.
  4. Look one up with GET /applications/{application_id}, as an ApplicationOut, or answer 404 with a detail that names the id when there's no such application.

Check your work

Run the tests from the exercise folder, with the virtual environment on:

pytest

No server needs to be running: TestClient hands each request straight to the app. At first all 17 tests fail. That's expected: each piece you finish turns its tests green. A failing test's message says what it sent, what it expected and what came back, for example POST /applications with "age": 17 should answer 422, but it answered 404 with {"detail":"Not Found"}.

To try the API yourself, start it with fastapi dev main.py and open http://127.0.0.1:8000/docs. Each route you add appears there under applications, and your two models appear under Schemas at the bottom. Stop the server with Ctrl+C.

Hints

  • Every rule goes on its field. Field Rules: Lengths, Ranges and Choices shows Field with min_length, max_length and ge, Literal for a fixed set of choices, and EmailStr. FastAPI then answers every broken rule with a 422 before your route runs, so the route never checks a field by hand.
  • A default makes a field optional. Request Models with Pydantic gives has_yard the default False.
  • Two models, two jobs. Response Models: Choosing What Goes Out writes one model for what comes in and one for what goes out. The body is an ApplicationIn, so a status or staff_notes in it is dropped, and response_model=ApplicationOut on the decorator drops staff_notes from the answer.
  • Build the application to keep from the model. model_dump() turns the ApplicationIn into a dictionary you can add the id, the status and the notes to, as Taking JSON In: Your First Request Body did for a game.
  • Raise the 404, don't return it, as When It Isn't There: HTTPException and 404 shows.

When you're done

Every test is green: pytest's last line says 17 passed. On the docs page, POST /applications with Sam's body answers 201 with:

{"id":4,"name":"Sam","email":"sam@example.com","age":29,"pet_name":"Juniper","pet_type":"cat","has_yard":false,"status":"received"}

Now send it again with "age": 15 and "pet_type": "hamster". The answer is 422, with an entry for each broken rule: ["body", "age"] and ["body", "pet_type"], and not one line of your route ran.

Look back at your two models. If the center started asking for a phone number that staff may see but the applicant's answer shouldn't show, which model would change, and which would stay the same?

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-fastapi-pet-adoption-applications), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-fastapi-pet-adoption-applications.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-fastapi-pet-adoption-applications, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Rules on what comes in and a list of what goes out are how real APIs stay trustworthy: bad data never reaches your code, and private data never reaches the caller.

Key terms

Related