Learning Python Through FastAPI (Your First API)
If you're coming from a Java background like me, switching to Python for AI can feel weird at first.
You’re used to:
Then Python hits you with:
So instead of learning Python the boring way… 👉 I decided to learn it by building an API
🧠 Why FastAPI?
For an aspiring AI Engineer, FastAPI is perfect because:
⚙️ Step 1 — Setup Your Environment
python -m venv myenvironment
Activate it (Windows):
myenvironment\Scripts\activate
Install dependencies:
pip install fastapi uvicorn
👉 Important:
▶️ Step 2 — Your First API
Create main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def greet():
return "Welcome to Zimma FastAPI!"
Run the server:
uvicorn main:app --reload
Open: 👉 http://127.0.0.1:8000 👉 http://127.0.0.1:8000/docs (Swagger UI)
⚠️ Common Beginner Mistake (You Hit This 😄)
You typed:
unicorn main:app --reload
❌ Wrong ✅ Correct:
uvicorn main:app --reload
📦 Step 3 — Understanding Models (Java Mindset)
In Java, you'd create an Entity or DTO.
In Python, we use Pydantic.
Create models.py:
from pydantic import BaseModel
class Product(BaseModel):
id: int
name: str
description: str
price: float
quantity: int
👉 This gives you:
🗂️ Step 4 — Building a Simple Product API
from fastapi import FastAPI
from models import Product
app = FastAPI()
products = [
Product(id=1, name="Laptop", description="High-performance laptop", price=999.99, quantity=10),
Product(id=2, name="Smartphone", description="Powerful camera phone", price=499.99, quantity=20),
]
🔍 GET All Products
@app.get("/products")
def get_products():
return products
🔎 GET Product by ID
@app.get("/products/{id}")
def get_product(id: int):
for product in products:
if product.id == id:
return product
return {"message": "Product not found"}
➕ POST (Create Product)
@app.post("/products")
def create_product(product: Product):
products.append(product)
return product
✏️ PUT (Update Product)
@app.put("/products/{id}")
def update_product(id: int, updated_product: Product):
for index, product in enumerate(products):
if product.id == id:
products[index] = updated_product
return updated_product
return {"message": "Product not found"}
❌ DELETE Product
@app.delete("/products/{id}")
def delete_product(id: int):
for index, product in enumerate(products):
if product.id == id:
del products[index]
return {"message": "Product deleted"}
return {"message": "Product not found"}
🖼️ Bonus — Adding Image Support
Update your model:
class Product(BaseModel):
id: int
name: str
description: str
price: float
quantity: int
image_url: str
👉 Example:
Product(
id=1,
name="Laptop",
description="High-performance laptop",
price=999.99,
quantity=10,
image_url="https://example.com/laptop.jpg"
)
What You Just Learned
Without realizing it, you covered:
👉 This is already equivalent to a mini Spring Boot app
🧭 Why This Matters for AI Engineers
Most AI systems today are not just models.
They are:
Frameworks like FastAPI are used to: