LearnFrenzy
Sign in Take a free test

Python Programming interview · Set 16 of 19

Python Web Development and REST APIs

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

From request to response

Web interviews follow a request: routing, validation, business logic, database, response and status code — plus security and deployment. Pick one framework and know it deeply, while understanding when the others fit.

  • FrameworksDjango, Flask and FastAPI trade-offs.
  • APIsREST design, validation and status codes.
  • ProductionORM, auth, ASGI and deployment.

Most Python backend jobs use Django, Flask or FastAPI. Interviewers want you to know when each fits, how a request flows through your code, and how to build an API that validates input, talks to a database and stays secure.

1. Flask vs Django vs FastAPI — how do you choose?

Django is “batteries included”: ORM, admin panel, authentication, forms and migrations — great for full products and content-heavy sites. Flask is a minimal micro-framework where you pick the pieces — good for small services and learning. FastAPI is a modern async framework built on type hints and Pydantic, with automatic validation and OpenAPI docs — the popular choice for APIs and AI/ML services.


2. Build a small REST API with validation in FastAPI.

Type hints define the request and response shapes; FastAPI validates input, converts types, returns clear 422 errors and generates interactive docs at /docs.

from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field

app = FastAPI()

class TaskIn(BaseModel):
    title: str = Field(min_length=3, max_length=120)
    priority: int = Field(default=3, ge=1, le=5)

class Task(TaskIn):
    id: int

TASKS: dict[int, Task] = {}

@app.post("/tasks", response_model=Task, status_code=status.HTTP_201_CREATED)
def create_task(task: TaskIn):
    new = Task(id=len(TASKS) + 1, **task.model_dump())
    TASKS[new.id] = new
    return new

@app.get("/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
    if task_id not in TASKS:
        raise HTTPException(status_code=404, detail="Task not found")
    return TASKS[task_id]

3. What makes an API RESTful? Which status codes should you use?

Resources are nouns with URLs (/orders/42), HTTP methods are verbs (GET reads, POST creates, PUT/PATCH update, DELETE removes), requests are stateless, and responses use proper status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests, 500 Server Error.


4. What is an ORM? Show SQLAlchemy usage.

An Object-Relational Mapper maps tables to classes and rows to objects, so you query with Python instead of raw SQL strings, get protection from SQL injection through parameters, and keep migrations in code (Alembic). Know the SQL it generates to avoid slow queries such as N+1.

from sqlalchemy import String, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session

class Base(DeclarativeBase): ...

class Student(Base):
    __tablename__ = "students"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(80))
    cgpa: Mapped[float]

with Session(engine) as session:
    toppers = session.scalars(select(Student).where(Student.cgpa >= 9).order_by(Student.name)).all()

5. WSGI vs ASGI?

WSGI is the traditional synchronous interface between Python apps and web servers (Gunicorn, uWSGI) — one request per worker at a time; Flask and classic Django use it. ASGI is its async successor (Uvicorn, Hypercorn) supporting async endpoints, WebSockets and long-lived connections; FastAPI and modern Django support it.


6. How do you add authentication to an API?

Common approaches: session cookies for browser apps (Django's default), and token-based auth for APIs — usually OAuth2 with JWT access tokens sent in the Authorization: Bearer header. Hash passwords with bcrypt or Argon2, keep tokens short-lived, use HTTPS everywhere and check permissions on every endpoint, not just login.

from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer

oauth2 = OAuth2PasswordBearer(tokenUrl="login")

def current_user(token: str = Depends(oauth2)) -> User:
    payload = decode_and_verify_jwt(token)      # raise 401 if invalid or expired
    return load_user(payload["sub"])

@app.get("/me")
def me(user: User = Depends(current_user)):
    return {"name": user.name}

7. What is dependency injection in FastAPI?

Depends() declares what an endpoint needs — a database session, the current user, settings — and FastAPI creates and passes it in, handling cleanup for yield dependencies. It keeps endpoints small and makes testing easy, because dependencies can be overridden with fakes.

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/students")
def list_students(db: Session = Depends(get_db)):
    return db.scalars(select(Student)).all()

8. How do you deploy a Python web app?

Package it in a Docker image with pinned dependencies; run it under a production server (Gunicorn with Uvicorn workers for ASGI) behind a reverse proxy or load balancer; configure through environment variables; run database migrations as a release step; add health checks, logging and metrics; and scale horizontally with several instances.

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["gunicorn", "app.main:app", "-k", "uvicorn.workers.UvicornWorker", "-w", "4", "-b", "0.0.0.0:8000"]

Remember

Key points

  • Validate every input

    Pydantic models at the API edge.

  • Right status codes

    201 for creates, 404, 422 and 429 used correctly.

  • Parameterised queries

    ORMs prevent SQL injection.

  • Authorise every endpoint

    Authentication alone is not enough.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is CORS and when do you need it? Basic

    A browser rule that blocks a page from calling an API on another origin unless the API allows it with CORS headers. Configure allowed origins explicitly; avoid * with credentials.

  2. 2 PUT vs PATCH? Basic

    PUT replaces the whole resource; PATCH changes only the fields sent.

  3. 3 How do you paginate an API? Intermediate

    Offset/limit for simple cases; cursor-based (keyset) pagination for large or changing data, returning a next_cursor.

  4. 4 How do you run background jobs from a web request? Intermediate

    For small work, FastAPI BackgroundTasks; for anything important or slow, a task queue (Celery, RQ, Dramatiq) with retries and monitoring.

  5. 5 What is the Django ORM select_related vs prefetch_related? Advanced

    select_related uses a SQL join for foreign keys (one query); prefetch_related runs a second query for many-to-many or reverse relations and joins in Python. Both fix N+1 queries.

  6. 6 How do you version an API? Intermediate

    Usually in the URL (/v1/orders) or a header; keep old versions running until clients migrate and document deprecations.

Preparing with friends?

Share this page with your study group or placement batch.

Popular