Layered REST API for Text Condensing with FastAPI
Data Structure DesignModel answerLast updated
Design a small FastAPI service that accepts text, returns a placeholder-generated summary, validates input, handles errors, and keeps a bounded in-memory history, using clear layers.
Task
Build a small HTTP service in Python with FastAPI that condenses text. The condensing logic can be a simple stand-in (no real model is required), but the service around it should look like something you would be comfortable shipping.
Contract
- Endpoint:
POST /summarize - Request body (JSON):
{ "text": string } - Response body (JSON):
{ "summary": string } - Every request and its resulting response must be kept in memory. No database.
Engineering expectations
- Separate the code into a router layer, a service layer and a models layer.
- Use type hints everywhere.
- Validate requests and shape responses with Pydantic models.
- Deal sensibly with invalid input and with unexpected failures.
- Keep the code modular, readable and simple.
What to deliver
- The proposed directory and file layout.
- The code for each file.
- A short explanation of your design choices (validation, error boundaries, state handling, testability).
Hints
Hint 1
Keep the HTTP concerns (status codes, HTTPException) in the router only; the service should raise domain exceptions and know nothing about HTTP.
Hint 2
In-memory state is shared across requests, and sync FastAPI endpoints run in a threadpool. Think about what protects the store from races and what stops it from growing forever.
Hint 3
Let Pydantic reject bad input (missing field, wrong type, blank or oversized text, extra fields) and add a global exception handler so unexpected errors are logged but never leak stack traces.
Hint 4
Inject the service and store with Depends so a test can override them with fakes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The text-condensing step is deliberately trivial. What matters is the service engineering around it:
- Layering. The router translates HTTP to and from function calls. The service holds the logic. Models define the contract. Storage hides behind a small class.
- Validation at the edge. Pydantic rejects malformed input before any of your code runs, returning a structured 422.
- Error boundaries. Expected failures map to specific status codes. Unexpected ones are logged server-side and return a generic 500.
- Concurrency awareness. Sync endpoints run in a threadpool, so shared state needs a lock.
- Bounded memory. Unlimited in-memory history is effectively a memory leak, so cap it.
- Testability. Dependencies come in via
Depends, so tests can useapp.dependency_overrides.
File layout
app/
├── __init__.py
├── main.py # app factory, global exception handler
├── models.py # request/response/record schemas
├── storage.py # thread-safe bounded store
├── dependencies.py # singleton wiring
├── routers/
│ ├── __init__.py
│ └── summarize.py # HTTP only
└── services/
├── __init__.py
└── summarizer.py # logic + placeholder model
Code
app/models.py
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, field_validator
MAX_TEXT_LENGTH = 50_000
class SummarizeRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(..., min_length=1, max_length=MAX_TEXT_LENGTH)
@field_validator("text")
@classmethod
def not_blank(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("text must not be blank")
return v
class SummarizeResponse(BaseModel):
summary: str
class SummaryRecord(BaseModel):
id: int
text: str
summary: str
created_at: datetime
app/storage.py
import threading
from collections import deque
from datetime import datetime, timezone
from itertools import count
from app.models import SummaryRecord
class InMemorySummaryStore:
"""Thread-safe store; oldest entries are dropped when full."""
def __init__(self, max_items: int = 1_000) -> None:
self._items: deque[SummaryRecord] = deque(maxlen=max_items)
self._ids = count(1)
self._lock = threading.Lock()
def add(self, text: str, summary: str) -> SummaryRecord:
with self._lock:
rec = SummaryRecord(
id=next(self._ids), text=text, summary=summary,
created_at=datetime.now(timezone.utc),
)
self._items.append(rec)
return rec
def all(self) -> list[SummaryRecord]:
with self._lock:
return list(self._items)
app/services/summarizer.py
import re
from app.storage import InMemorySummaryStore
_SPLIT = re.compile(r"(?<=[.!?])\s+")
class SummarizationError(Exception):
"""Summary could not be produced."""
class SummarizerService:
def __init__(self, store: InMemorySummaryStore,
max_sentences: int = 2, max_chars: int = 500) -> None:
self._store = store
self._max_sentences = max_sentences
self._max_chars = max_chars
def summarize(self, text: str) -> str:
try:
summary = self._generate(text)
except Exception as exc:
raise SummarizationError("summarization failed") from exc
self._store.add(text=text, summary=summary)
return summary
def _generate(self, text: str) -> str:
parts = _SPLIT.split(text)
summary = " ".join(parts[: self._max_sentences])
if len(summary) > self._max_chars:
summary = summary[: self._max_chars].rstrip() + "..."
return summary
app/dependencies.py
from functools import lru_cache
from app.services.summarizer import SummarizerService
from app.storage import InMemorySummaryStore
@lru_cache
def get_store() -> InMemorySummaryStore:
return InMemorySummaryStore()
@lru_cache
def get_summarizer() -> SummarizerService:
return SummarizerService(store=get_store())
app/routers/summarize.py
import logging
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from app.dependencies import get_summarizer
from app.models import SummarizeRequest, SummarizeResponse
from app.services.summarizer import SummarizationError, SummarizerService
logger = logging.getLogger(__name__)
router = APIRouter(tags=["summarization"])
@router.post("/summarize", response_model=SummarizeResponse)
def summarize(
request: SummarizeRequest,
service: Annotated[SummarizerService, Depends(get_summarizer)],
) -> SummarizeResponse:
try:
return SummarizeResponse(summary=service.summarize(request.text))
except SummarizationError:
logger.exception("Summarization failed")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to generate summary",
)
app/main.py
import logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from app.routers.summarize import router
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def create_app() -> FastAPI:
app = FastAPI(title="Summarization Service", version="1.0.0")
app.include_router(router)
@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception) -> JSONResponse:
logger.exception("Unhandled error on %s", request.url.path)
return JSONResponse(status_code=500,
content={"detail": "Internal server error"})
return app
app = create_app()
Run with uvicorn app.main:app --reload.
Why this works
- Contract enforcement. Malformed JSON, a missing or non-string
text, blank or oversized text and unknown fields all produce a 422 automatically.response_modelguarantees the output is exactly{ "summary": string }. - Error layering. The service converts any model failure into
SummarizationError; the router maps it to a safe 500; anything else reaches the global handler, which logs the traceback and returns a generic message. - State safety. A lock guards the deque, and
maxlenbounds memory with O(1) append and eviction. - Testing. Override
get_summarizerwith a fake, or constructSummarizerServicedirectly with a fresh store.
Trade-offs
- Process-local state. With multiple Uvicorn workers each has its own history, and a restart loses everything. A real deployment would use a database or cache; the store interface makes that swap easy.
- Sync vs async. A CPU-bound placeholder fits a sync endpoint (threadpool). If a real model is called over the network, use an async client and
async def, and swap the threading lock for anasyncio.Lockor avoid shared mutable state. - Complexity. Each request costs O(n) in the text length for splitting; storage operations are O(1).
Common mistakes
- Putting business logic or storage inside the route function.
- Using a bare global list with no lock and no size cap.
- Returning
str(exc)or tracebacks to clients. - Catching
Exceptionin the router and hiding validation errors that Pydantic would handle better. - Creating a new store per request via
Dependswithout caching, so nothing persists. - Trusting input length; without
max_length, a single request can exhaust memory.
Possible follow-ups
- Add
GET /summarieswith pagination. - Add request IDs and structured logging.
- Add rate limiting and auth.
- Write tests with
TestClientcovering 200, 422 and 500 paths.