Day 3 — FastAPI: build your own API
Why / क्यों
English: Until now you used other people's APIs. FastAPI lets you build your own. Every AI product — RAG chatbot or agent — runs behind an API server that websites and apps call.
Hindi: अब तक दूसरों का API use किया। FastAPI से अपना API बनाते हो। हर AI product (RAG chatbot, agent) एक API server के पीछे चलता है, जिसे website और app call करते हैं।
How a request flows / request कैसे चलती है
flowchart LR
U[Browser / App] -->|GET or POST| S[FastAPI server]
S --> V{Pydantic check}
V -->|valid| F[Your function]
V -->|invalid| E[422 error]
F -->|JSON| U
F -.->|calls| X[External API e.g. weather]
Step 1 — Install
pip install fastapi uvicorn
FastAPI builds the API; uvicorn is the server that runs it.
Step 2 — Your first API with GET and POST
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.get("/")
def home():
return {"message": "Hello, your first API is live!"}
class ChatRequest(BaseModel):
user: str
question: str
@app.post("/chat")
def chat(req: ChatRequest):
return {"reply": f"Hi {req.user}, you asked: {req.question}"}
Save as day3_fastapi.py, then run:
uvicorn day3_fastapi:app --reload
Open http://127.0.0.1:8000 and the auto docs at http://127.0.0.1:8000/docs.
Step 3 — Test POST in /docs
{
"user": "Student",
"question": "What is RAG?"
}
Remove the question field and try again → 422 Unprocessable Entity. Pydantic blocked the bad request before your code ran.
Step 4 — Weather endpoint (your API calls another API)
import requests
CITIES = {"delhi": (28.61, 77.21), "mumbai": (19.07, 72.88)}
@app.get("/weather/{city}")
def weather(city: str):
coords = CITIES.get(city.lower())
if coords is None:
return {"error": f"{city} not supported yet"}
lat, lon = coords
url = "https://api.open-meteo.com/v1/forecast"
params = {"latitude": lat, "longitude": lon, "current_weather": True}
data = requests.get(url, params=params).json()
return {"city": city, "temperature_c": data["current_weather"]["temperature"]}
Test: http://127.0.0.1:8000/weather/delhi
Agent link
This endpoint is exactly what an AI agent's tool looks like. Later, the LLM will decide when to call it.
Quiz / अपने आप को test करो
1. GET vs POST?
GET asks for data; POST sends data to the server.
2. What does --reload do?
Restarts the server automatically whenever you save the code.
3. What is /docs?
Auto-generated Swagger UI to see and test every endpoint.
4. When do you get 422?
When data arrives in the wrong format and Pydantic rejects it.
5. What is {city} in /weather/{city}?
A path parameter — the value in the URL is passed to the function.