Concept Explanation
In the past, Flask and Django were the only ways to build websites in Python. But modern apps need to be Fast (as fast as Node.js or Go) and Safe (detecting errors before they happen).
FastAPI is a modern web framework that uses "Type Hinting" (name: str) to automatically check your data. If someone tries to send a number where you expected a piece of text, FastAPI will automatically reject the request with a beautiful error message before your code even runs. It is the gold standard for building Microservices.
Syntax or Core Structure
The FastAPI Application
FastAPI uses the uvicorn server to run.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 1. Define a Data Model using Pydantic
class User(BaseModel):
id: int
username: str
email: str
# 2. Define a Route
@app.post("/users/")
async def create_user(user: User):
# 'user' is already a safe Python object here!
return {"message": f"User {user.username} created"}
Code Example #1 (Basic)
Path Parameters and Query Parameters.
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
# Try: /items/5?q=hello
Code Example #2 (Intermediate)
Dependency Injection: Reusing logic (like database connections) across many routes.
from fastapi import Depends
def get_db():
print("Opening DB Connection...")
yield "DATABASE_OBJECT"
print("Closing DB Connection...")
@app.get("/data")
async def get_data(db: str = Depends(get_db)):
return {"db_status": "Connected"}
Real World Example
Dockerized Price Checker: Putting your FastAPI app into a "Container" so it runs exactly the same on your laptop as it does on a massive server in the cloud.
# 🐳 Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY . .
RUN pip install fastapi uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Common Mistakes
- Forgetting Async: FastAPI is built for speed using
async def. If you use normaldef, the app will still work, but it won't be able to handle thousands of users at once. - Skipping Models: Not using Pydantic models for your POST requests. This makes your app vulnerable to bad data and hackers.
- Missing Documentation: Beginners forget that FastAPI creates an automatic documentation page at
/docs. Use it! It saves you hours of testing with Postman.
Best Practices
- Automatic Docs: Always visit
http://localhost:8000/docswhile developing to test your API visually. - Environment Variables: Never put database passwords in your code. Use
.envfiles and thepython-dotenvlibrary. - Version your API: Start your URLs with
/v1/. This way, you can change your app later without breaking things for existing users.
Practice Exercises
- The Greeting API: Create a GET route that takes a "name" parameter and returns
{"hello": name}. - The Validator: Create a Pydantic model for a "Product" (Name, Price, Category). Create a POST route that accepts this model and prints the Price to the console.
- The Dependency: Create a dependency that checks if a request has a special "API-Key" in the header. If it's missing, return an error.