Build a FastAPI endpoint that accepts JSON, validates input, handles errors gracefully and returns structured responses. The foundation of every AI service.
How one request travels through the echo endpoint
Step 1 of 5
Client request
A client sends POST /api/echo with a JSON body such as {"message": "hello", "uppercase": true}.
Step 2 of 5
Route match
FastAPI matches the method and path. A GET to the same path stops here with 405 method not allowed.
Step 3 of 5
Validate body
Pydantic checks the body against EchoRequest. A missing message or the wrong type returns a 422 with the field that failed.
Step 4 of 5
Handler logic
Your function runs only on valid input. It applies uppercase when asked and works out the length. Unexpected errors are caught here.
Step 5 of 5
Structured reply
The handler returns an EchoResponse with original, echoed and length, so every success has the same shape.
Validation happens before your code runs, so bad input never reaches the handler.
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.py
~108 tokens
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.