🧩 1. Introduction to FastAPI¶
🚀 What is FastAPI and Why Use It?¶
FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints.
🔥 Key Benefits:¶
- Speed: FastAPI is one of the fastest Python frameworks, rivaling Node.js and Go.
- Type Safety: Uses Python type hints for automatic request validation and documentation.
- Automatic Docs: Generates interactive Swagger and ReDoc documentation out of the box.
- Async-Ready: Built on Starlette and Pydantic, it supports asynchronous programming natively.
- Developer Experience: Minimal boilerplate, great editor support, and fast iteration.
🧠 Use Cases:¶
- RESTful APIs
- Microservices
- Backend for web/mobile apps
- ML model serving
- Real-time apps (via WebSockets)
🛠️ Installing FastAPI and Uvicorn¶
FastAPI is just the framework. To run it as a web server, you’ll need Uvicorn, an ASGI server.
✅ Step-by-Step Installation¶
-
Create a virtual environment (recommended):
python -m venv fastapi-env source fastapi-env/bin/activate # On Windows: fastapi-env\Scripts\activate -
Install FastAPI and Uvicorn:
pip install fastapi uvicorn -
Verify installation:
python -m pip show fastapi python -m pip show uvicorn
You’re now ready to build your first API.
👋 First “Hello World” Endpoint¶
Let’s write a minimal FastAPI app that returns a greeting.
📄 Create a file called main.py:¶
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
🧪 Run the server:¶
uvicorn main:app --reload
main: the filename (without.py)app: the FastAPI instance-reload: enables hot-reloading during development
🌐 Visit in your browser:¶
http://127.0.0.1:8000/→ returns JSON:{"message": "Hello, FastAPI!"}http://127.0.0.1:8000/docs→ Swagger UI (interactive API docs)http://127.0.0.1:8000/redoc→ ReDoc UI (alternative docs)
🧪 Try It Yourself¶
Change the message or add another route:
@app.get("/greet/{name}")
def greet_user(name: str):
return {"message": f"Hello, {name}!"}
Visit http://127.0.0.1:8000/greet/your_name and see the personalized response.