C
Python/Web/Lesson 25

Getting Started with FastAPI

1 hr·theory
Python

Getting Started with FastAPI

🎯 After Reading This Lesson

By the end of this lesson, you will be able to confidently do the following 3 things.

  • ✅ Why Python became the standard language for AI/data
  • ✅ Setting up venv + requirements.txt for Python 3.x
  • ✅ Four built-in functions: print / input / type / dir

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

FastAPI — Code + Output

FastAPI = Modern Python web framework. Automatic type hint validation + automatic Swagger UI generation. Async-first standard.


1. Installation + Hello World

bash
$ pip install fastapi uvicorn
python
# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def index():
    return {"message": "Hello!"}
bash
$ uvicorn main:app --reload
# http://localhost:8000 → {"message": "Hello!"}
# http://localhost:8000/docs → Automatic Swagger UI

2. Path Parameters

python
@app.get("/items/{id}")              # /items/42 → id=42
def item(id: int):                 # Type hint = automatic conversion
    return {"id": id, "name": f"Item {id}"}

# /items/abc → 422 Error (automatic validation)

3. Query Parameters

python
@app.get("/search")                 # /search?q=python&limit=10
def search(q: str, limit: int = 5):
    return {"query": q, "count": limit}

4. POST + Request Body (Pydantic)

python
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int
    email: str | None = None

@app.post("/users")
def create(u: User):                # JSON → automatic validation
    return {"created": u.name}

# Request: POST /users {"name": "Hong Gil-dong", "age": 28}
# Response: {"created": "Hong Gil-dong"}
# Invalid JSON → 422 Error automatically

5. Async + DB Call

python
@app.get("/users/{id}")
async def fetch(id: int):
    user = await db.fetch_one("SELECT * FROM users WHERE id = $1", id)
    if not user:
        raise HTTPException(404, "Not found")
    return user

One-line Summary

@app.get/post + type hints + Pydantic model — that's all you need for a REST API.

💻 FastAPI Basic Example
# pip install fastapi uvicorn
from fastapi import FastAPI, Query, Path
from typing import Optional

app = FastAPI(title="My API", version="1.0.0")

# Basic endpoint
@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

# Path parameters
@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

# Query parameters
@app.get("/search/")
def search(
    q: str,
    skip: int = 0,
    limit: int = Query(default=10, le=100)
):
    return {"q": q, "skip": skip, "limit": limit}

# Asynchronous endpoint
@app.get("/async/")
async def async_endpoint():
    return {"message": "Async response"}

# Run: uvicorn main:app --reload
# Docs: http://localhost:8000/docs (Swagger UI)
# Docs: http://localhost:8000/redoc (ReDoc)

💡 Key Points

1. Auto API docs: /docs, /redoc
2. Type hints → automatic validation
3. uvicorn: ASGI server

Python has a concise, readable syntax and is used across many domains. As an interpreted language, it can be run immediately in a REPL environment. Follow the PEP 8 coding style guide, and use Black/autopep8 for automatic formatting. Type hints improve code readability and IDE support. Manage packages with pip, and set up virtual environments with venv/conda.

🐍 Try It Yourself — Getting Started with FastAPI

Try running the concepts above as actual code. The fastest way to learn is to change values and see firsthand how things behave.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Asking AI Like This

Once you understand the concepts in this lesson, you can give AI specific instructions. Instead of a vague 'fix this,' a request with vocabulary — that's where token savings begin.

  • 'Migrate this Flask code to FastAPI'
  • 'Add a Pydantic model + dependency injection to this FastAPI endpoint'

Why This Reduces Tokens

Without knowing the concepts, even after receiving an AI response you end up asking 'What does that mean?' all over again. That 'asking again' is what eats tokens. Learn the concept once and the conversation ends in a single round.

Introduction to FastAPI - Python