Chapter 04 · AI-Powered Full Stack
Simple API for the App (Node or Python)
The UI should not call the AI vendor directly. Your API is the gatekeeper.
Why this matters
Browsers expose everything to the user. Keys, rate limits and logging belong on the server. A stub API first proves the plumbing without spending API credits.
What you will learn
You will add POST /api/ask (Next.js route handler or a small Express/FastAPI service), validate input length, return { answer: "…" } as plain JSON, and handle errors with clear messages.
How to do it
Pick one: Next.js Route Handler (fastest with our starter) or a separate FastAPI service. Document the choice.
Steps (do these in order)
- Step 1 — Define the contract. Request JSON: { "question": "string" }. Response JSON: { "answer": "string" }. Errors: { "error": "string" }.
- Step 2 — Validate. Reject empty questions and questions longer than 500 characters. Return HTTP 400 with a clear message.
- Step 3 — Stub answer. For now return: "Stub: we received your question about <trimmed text>. AI comes in chapter 6."
- Step 4 — Wire the form. On Submit, fetch('/api/ask', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({question}) }). Show answer or error in the UI.
- Step 5 — Log safely. Log only length and a request id — not full customer text in production logs if it may hold PII.
Practice
- Test with curl or Thunder Client: good question, empty question, too-long question.
- Write the three HTTP status codes you return (200 / 400 / 500) in the README.