Module 04 / Project 01 — Hello FastAPI¶
Home: README
Learn Your Way¶
| Read | Build | Watch | Test | Review | Visualize | Try |
|---|---|---|---|---|---|---|
| — | This project | Walkthrough | — | Flashcards | — | — |
Focus¶
First endpoint, running with uvicorn, automatic interactive docs at /docs.
Why this project exists¶
FastAPI is the fastest way to build a Python web API. This project gets you from zero to a running server in minutes. You will create your first endpoint, learn how FastAPI turns decorators into routes, and discover the automatic documentation that makes testing your API effortless.
Run¶
Then open your browser to:
- http://127.0.0.1:8000 — your root endpoint
- http://127.0.0.1:8000/docs — interactive Swagger UI documentation
- http://127.0.0.1:8000/items/42?q=hello — path and query parameters in action
Press Ctrl+C in the terminal to stop the server.
Expected output¶
Visiting http://127.0.0.1:8000 returns:
Visiting http://127.0.0.1:8000/items/42?q=hello returns:
Visiting http://127.0.0.1:8000/health returns:
Alter it¶
- Add a new
GET /greet/{name}endpoint that returns{"greeting": "Hello, {name}!"}. - Add an optional query parameter
uppercase(bool) to the greet endpoint. When true, return the greeting in all caps. - Add a
GET /add/{a}/{b}endpoint that takes two integers and returns their sum.
Break it¶
- Change the decorator from
@app.get("/")to@app.get(remove the parentheses and path). What error do you get? - Try visiting
http://127.0.0.1:8000/items/not-a-number. What does FastAPI return? Why? - Change
item_id: inttoitem_id: strin the function signature. How does the/docspage change?
Fix it¶
- After removing the parentheses, put them back and add the path string. Confirm the endpoint works again.
- The 422 error from passing a non-integer is FastAPI's automatic validation. There is nothing to fix because validation is the correct behavior. Explain why in your notes.
- Restore the
inttype hint. Notice how FastAPI uses Python type hints to validate inputs automatically.
Explain it¶
- What does the
@app.get("/")decorator do? What happens if two routes have the same path? - What is the difference between a path parameter (
/items/{item_id}) and a query parameter (?q=hello)? - Where does the interactive documentation at
/docscome from? Did you write any HTML? - What role does
uvicornplay? Why can't you just run a FastAPI app withpython app.pywithout it?
Mastery check¶
You can move on when you can:
- start the server and visit
/docswithout looking at these instructions, - add a new endpoint with both path and query parameters,
- explain what uvicorn does and why FastAPI needs it,
- describe how type hints control validation.
Related Concepts¶
Next¶
Continue to 02-crud-api.