Exercise: Community Garden Requests
Answer Greenleaf Community Garden's requests by hand in plain Python, with a function that reads each request's method, path and query string and returns the right status code and body, a 404, 400 or 405 included, and let pytest check every answer.
Apprentice · REST API · Web Development · Python · Updated
Neighbors keep phoning Greenleaf Community Garden with the same questions: "Which plots are free?", "Who has plot 7?". You'll answer them the way an API does, in plain Python with no framework: one function that reads a request's method, path and query string, and gives back a status code and a body. It's the routing a framework does for you, done once by hand, and tests check every answer as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-community-garden-requests, 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-community-garden-requests.git
Git makes a folder, exercise-fastapi-community-garden-requests, 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:
garden.py: the functionhandle(method, path), for you to finish.data.py: the garden's eight plots, in the listPLOTS. A free plot'sgardenerisNone.try_it.py: sends every request in the list below tohandleand prints each answer. Ready to use.tests/test_garden.py: the tests, which send each request tohandle. You don't need to change it.requirements.txtandpytest.ini: pytest at an exact version, and where pytest finds the tests and your code.
What to do
handle(method, path) gets the method in capital letters, such as "GET", and the path with its query string, such as "/plots?free=true". It returns a tuple of the status code and the body, such as (200, PLOTS). For now it answers every request with 501, "I don't do that yet". The comment at the top of garden.py lists every request it should answer:
GET /plots 200, every plot in data.py
GET /plots?free=true 200, only the free plots (gardener None): plots 2, 4 and 8
GET /plots?free=false 200, only the plots that have a gardener: plots 1, 3, 5, 6 and 7
GET /plots?free=maybe 400, {"detail": "free must be true or false."}
(any value of free other than true or false gets this answer)
GET /plots/7 200, plot 7 (every plot's number works the same way)
GET /plots/99 404, {"detail": "There's no plot 99."}
GET /plots/seven 400, {"detail": "A plot number is a whole number."}
POST /plots 405, {"detail": "Method Not Allowed"}
DELETE /plots/7 405, {"detail": "Method Not Allowed"}
(any method other than GET, for /plots or one plot, gets this answer)
GET /tools 404, {"detail": "Not Found"}
(any other path gets this answer, whatever the method)
The plots in a list keep the order they have in PLOTS.
- Every plot. Answer
GET /plotswith 200 andPLOTS. - The free filter. Split the query string off the path, and answer
?free=trueand?free=falsewith the plots that match, or 400 for any other value. - One plot by its number, such as
GET /plots/7, with a 404 that names the number when no plot has it, and a 400 when the number isn't all digits. - The wrong method and the wrong path. Any method other than GET on
/plotsor one plot answers 405, and any other path answers 404.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
At first all 10 tests fail. That's expected: each request you answer turns its test green. A failing test's message says what it sent, what it expected and what came back, for example GET /plots should answer 200, but it answered 501 with {'detail': 'Not written yet'}.
To see your answers yourself, run python try_it.py: it prints each request from the list and what handle answered.
Hints
- Split the query string off first.
urlsplit(path)gives.pathand.query, andparse_qsturns the query into a dictionary, as HTTP in Plain Words: Requests and Responses shows. Both are imported for you. Its values are text in lists, so the value offreeisquery["free"][0], the text"true". - Cut the number off the path. Routing by Hand, and Why Frameworks Exist reads plot 7 with
startswith,removeprefixandisdigit(), thenint(). - Check the path before the method.
/toolsis a 404 whatever its method, andPOST /plotsis a 405 because the garden has/plots, as Status Codes and Headers reads them: "that address doesn't take that method". - One helper per route keeps
handleshort, such aslist_plots(query)andget_plot(number_text), each returning its own status and body.
When you're done
Every test is green: pytest's last line says 10 passed. And python try_it.py prints, among its lines:
GET /plots/7 -> (200, {'number': 7, 'size': 'small', 'gardener': 'Lena', 'growing': 'strawberries'})
GET /plots/99 -> (404, {'detail': "There's no plot 99."})
DELETE /plots/7 -> (405, {'detail': 'Method Not Allowed'})
Now count your lines. Two routes and four error answers took you about thirty. In the next chapter, FastAPI answers the same requests from a few short functions, and you'll see which of your lines it writes for you.
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.
On GitHub, click +, then New repository. Name it (for example
exercise-fastapi-community-garden-requests), choose Public, and click Create repository. Leave out the README: your folder already has one.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-community-garden-requests.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-fastapi-community-garden-requests, 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
Reading the method, cutting up the path and the query string, and choosing a status code for every case is the work behind every API request, and now that you've done it by hand, you'll know exactly what FastAPI is doing when it does it for you.