TECHNOLOGIESTieInn Technologies

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 HTTPException with a clear message.
  • --reload is for development only.
  • Blocking work in an endpoint slows every other request; see async.
  • No /health endpoint makes deployment checks harder.

Want the full lesson with step-by-step examples, a project and a certificate? Shipping AI Apps course, ₹180 →

Questions

Open in Code Lab5 free questions
5 questions

    FastAPI basics: endpoints, request and response models

  1. Question 1easy

    Why shouldn't a website call the Gemini API directly from the browser?

  2. FastAPI basics: endpoints, request and response models

  3. Question 2easy

    With @app.get("/orders/{order_id}") and def get_order(order_id: int), what does GET /orders/32 do?

  4. FastAPI basics: endpoints, request and response models

  5. 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())
  6. FastAPI basics: endpoints, request and response models

  7. Question 4medium

    Your /ask endpoint catches a model error and returns 200 with {"error": "model failed"}. What's wrong with that?

  8. FastAPI basics: endpoints, request and response models

  9. Question 5easy

    A client POSTs {"question": 42} to an endpoint whose model says question is a str with at least 3 characters. What happens?

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.