Day 01 Foundations

FastAPI Fundamentals: Build Your First API

FastAPI is the fastest way to build production-ready APIs in Python. In this lesson you'll install it, understand how it works, and build your first working endpoint.

~1 hour Hands-on Precision AI Academy

Today's Objective

A running FastAPI server with three endpoints: a health check, a text analysis endpoint that calls Claude, and a JSON response with proper status codes and error handling.

01
Section 2 · 10 min

Install and First Server

Install FastAPI and uvicorn (the server that runs it):

bash
bash
$ pip install fastapi uvicorn anthropic python-dotenv

Create main.py:

main.py
python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def health_check():
    return {"status": "ok", "service": "AI API"}

Run it:

bash
bash
$ uvicorn main:app --reload

Open http://localhost:8000 — you get your first response. Open http://localhost:8000/docs — you get auto-generated documentation you can run right in the browser.

01
Section 3 · 25 min

Add an AI Endpoint

Now build a real endpoint that accepts text and returns an AI-generated summary:

main.py
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import anthropic

app = FastAPI(title="AI Text API")
client = anthropic.Anthropic()

class SummarizeRequest(BaseModel):
    text: str
    max_words: int = 100

@app.get("/")
def health_check():
    return {"status": "ok"}

@app.post("/summarize")
def summarize(req: SummarizeRequest):
    if not req.text.strip():
        raise HTTPException(status_code=400, detail="text cannot be empty")

    msg = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=512,
        system=f"Summarize the text in {req.max_words} words or fewer. Return only the summary.",
        messages=[{"role": "user", "content": req.text}]
    )

    return {
        "summary": msg.content[0].text,
        "input_tokens": msg.usage.input_tokens,
        "output_tokens": msg.usage.output_tokens
    }

Test it at /docs — click the /summarize endpoint, click "Try it out," paste any text, hit Execute. You'll see the raw request and response.

20%

Want live instruction and hands-on projects? Join the AI bootcamp — 3 days, 5 cities.

Supporting References & Reading

Go deeper with these external resources.

FastAPI Docs
FastAPI Fundamentals: Build Your First API Official FastAPI documentation with examples and guides.
YouTube
FastAPI Fundamentals: Build Your First API FastAPI tutorials on YouTube
MDN
MDN Web Docs Comprehensive web technology reference

Day 1 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 2
Day 2 of the API Development for AI course