FastAPI basics: endpoints, request and response models
Shipping AI Apps · 10 questions
Short notes
Key idea
FastAPI turns Python functions into web endpoints. Pydantic models define what a request must contain and what a response returns, so bad input is rejected automatically and docs are generated for free.
Syntax
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Question(BaseModel):
text: str
user_id: int
class Answer(BaseModel):
reply: str
@app.get("/health")
def health():
return {"ok": True}
@app.post("/ask", response_model=Answer)
def ask(q: Question):
if not q.text.strip():
raise HTTPException(status_code=400, detail="empty question")
return Answer(reply=f"You asked: {q.text}")
Run: uvicorn main:app --reload; docs at /docs.
Example
Sending {"text": 5} without user_id returns a 422 error naming both problems before your function even runs.
Traps
- Returning internal errors (stack traces) to users; raise
HTTPExceptionwith a clear message. --reloadis for development only.- Blocking work in an endpoint slows every other request; see async.
- No
/healthendpoint makes deployment checks harder.
Want the full lesson with step-by-step examples, a project and a certificate? Shipping AI Apps course, ₹180 →
- Question 1easy
Why shouldn't a website call the Gemini API directly from the browser?
- Question 2easy
With @app.get("/orders/{order_id}") and def get_order(order_id: int), what does GET /orders/32 do?
- Question 3medium
What does this print?
from pydantic import BaseModel class AskResponse(BaseModel): answer: str sources: list[str] = [] print(AskResponse(answer="Within 10 days.").model_dump_json()) - Question 4medium
Your /ask endpoint catches a model error and returns 200 with {"error": "model failed"}. What's wrong with that?
- Question 5easy
A client POSTs {"question": 42} to an endpoint whose model says question is a str with at least 3 characters. What happens?
FastAPI basics: endpoints, request and response models
FastAPI basics: endpoints, request and response models
FastAPI basics: endpoints, request and response models
FastAPI basics: endpoints, request and response models
FastAPI basics: endpoints, request and response models
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.