FastAPI is a modern, high‑performance Python framework (Python 3.7+) that uses type hints for data validation and leverages two proven libraries:
| Component | Purpose |
|---|---|
| Starlette | Handles routing, websockets, middleware, and ASGI‑compatibility. |
| Pydantic | Validates request/response schemas via dataclasses (BaseModel). |
Why it matters
/docs) and ReDoc (/redoc) are auto‑generated from your code.Code snippet – instantiating the appfrom fastapi import FastAPI app = FastAPI()
ComparisonExpress.js (Node) and FastAPI both expose quick GET/POST routes, but FastAPI brings Python‑style type hints to the table.
| Step | What to do | Why it matters |
|---|---|---|
| Virtual env | python -m venv .venv |
Keeps your project’s packages isolated from the global Python installation. |
| Activate | source .venv/bin/activate (Unix) or .venv\Scripts\activate (Windows) |
Turns the virtual env on for the current shell session. |
| Install core libs | pip install fastapi uvicorn |
uvicorn is a lightweight ASGI server that keeps the app running in dev mode. |
| Run the server | uvicorn main:app --reload |
main = Python file name, app = FastAPI instance; --reload restarts automatically on code changes. |
| IDE | VS Code (demo used this) | Any editor works, but VS Code supports Python linting and FastAPI plugins. |
| Goal | Explanation | Minimal Code |
|---|---|---|
| Root | Return a friendly JSON payload. | python\[email protected]("/")\ndef read_root():\n return {"message": "Hello World"}\n |
| Path param | Pull a value from the URL itself; FastAPI casts it based on your type hint. | python\[email protected]("/user/{user_id}")\ndef read_user(user_id: int):\n return {"user_id": user_id}\n |
| Query param | Optional data appended after a ? token; you can give defaults or set Optional. |
python\[email protected]("/user")\ndef get_user(limit: int = 10, name: Optional[str] = None):\n return {"limit": limit, "name": name}\n |
| Conditional logic | Show how you can tailor the response depending on a query string. | python\[email protected]("/numbers")\ndef list_numbers(limit: int = 0):\n if limit:\n return list(range(limit))\n return list(range(100))\n |
Practical tip – If you navigate to http://localhost:8000/docs, the Swagger UI will let you test each of these endpoints directly in the browser.
FastAPI automatically transforms incoming JSON into a Pydantic model, validates it, and returns it back to you.
| Step | Explanation | Code |
|---|---|---|
| Create a model | Describes the shape and types of your data. | python\nclass User(BaseModel):\n id: int\n name: str\n age: int\n |
| POST endpoint | Accepts a User instance as its body. |
python\[email protected]("/create_post")\ndef create_user(user: User):\n # Normally you’d persist user to a DB\n return user\n |
| Docs | Visiting /docs will show a form where you can enter a JSON payload; it will also flag missing required fields. |