PYTHON FASTAPI · LESSON 2 OF 8
Paths, queries and Python types
Read URL inputs and reject invalid values before your function runs.
- Annotated
- Path
- Query
- 422
Your runnable checkpoint
Extract into a new practice folder. Each download includes complete source, requirements.txt and README.md. Stop any earlier server before running this example.
Create and activate a virtual environment as shown in lesson 1. Install with python -m pip install -r requirements.txt, then run fastapi dev main.py. Lessons 6–8 require TASK_API_KEY as explained in lesson 6.
1. Understand the concepts
A path identifies a resource: /courses/3. A query modifies a request: /search?q=Python&limit=2. FastAPI matches course_id to the placeholder in the route; other scalar parameters become query parameters.
Annotated combines a Python type with validation metadata. int converts valid numeric input; Path(gt=0) rejects zero and negative values. Query limits request size and makes the rules visible in /docs.
Defaults make parameters optional. Omitting q selects Python and omitting limit selects 5. Invalid input produces 422 with a detail array describing the location and reason. Your route function does not execute for those invalid inputs.
This checkpoint replaces main.py from lesson 1; it is a small independent example. Run every downloaded checkpoint in its own folder and stop the previous server before starting another.
2. Build and run
These are complete files, not fragments. Save them beside each other in the extracted project folder. Open http://127.0.0.1:8000/docs to send requests.
main.py
from typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/courses/{course_id}")
def course(course_id: Annotated[int, Path(gt=0)]):
return {"id": course_id}
@app.get("/search")
def search(q: Annotated[str, Query(min_length=2)] = "Python",
limit: Annotated[int, Query(ge=1, le=20)] = 5):
return {"query": q, "limit": limit}
requirements.txt
fastapi[standard]>=0.115,<1
pydantic>=2,<3
httpx>=0.27,<1
pytest>=8,<10
3. Check the result
- GET /courses/3 returns {"id":3}.
- GET /courses/zero and /courses/0 return 422.
- GET /search?limit=21 returns 422.
4. Practice independently
Make q required.
Show the explanation
Remove = "Python" from q. Keep required parameters before parameters with defaults.
When something goes wrong
For import errors, confirm the virtual environment is active and install requirements.txt using that environment’s Python. For 422, read the response detail and compare your input to the model. For 404, check the method, path and resource id. For 401 in later lessons, use Authorize in /docs with the same key configured on the server.
