All labs
Build a Production HTTP API
Build a FastAPI endpoint that accepts JSON, validates input, handles errors gracefully and returns structured responses. The foundation of every AI service.
Scenario
You're building the service that will later host your LLM endpoints. Before any AI, build a robust, validated, well-error-handled HTTP API.
Objective
Implement a POST /api/echo endpoint that validates input, returns structured output, and handles errors with proper status codes.
Starter code
Implement the TODOs to complete the lab.
main.pypython
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class EchoRequest(BaseModel):
message: str
uppercase: bool = False
class EchoResponse(BaseModel):
original: str
echoed: str
length: int
@app.post("/api/echo")
def echo(req: EchoRequest):
# TODO: implement echo logic
# - if uppercase, transform message
# - return EchoResponse
pass Solution hints
- 1Use req.uppercase to conditionally transform
- 2Return EchoResponse with original, echoed, length
- 3Add a try/except for unexpected errors
- 4Test with empty message — should it error?
Validation steps
Your implementation should pass these checks.
- POST /api/echo with {message: 'hello'} returns echoed 'hello', length 5
- POST /api/echo with {message: 'hello', uppercase: true} returns 'HELLO'
- POST /api/echo with empty body returns 422 validation error
- GET /api/echo returns 405 method not allowed
Run validation
This is a simulated validation environment. In production, this would run your code against the validation steps.