💻 Programming

FastAPI

A high-performance Python web API framework

📖 Detailed Explanation

FastAPI is a Python web framework created by Sebastian Ramirez in 2018, optimized for modern API development. Designed around Python 3.7+ type hints, it automatically generates API documentation (Swagger UI, ReDoc) from the code you write and even performs runtime data validation.

FastAPI's key feature is asynchronous (async/await) support built on Starlette. It delivers high performance comparable to Node.js and Go, and records top performance among Python web frameworks in the TechEmpower benchmarks. Synchronous code can be used alongside it, so compatibility with existing libraries is also excellent.

Data validation uses the Pydantic library. When you define request/response models as Python classes, JSON serialization, type validation, and error message generation are handled automatically. This greatly contributes to faster development and fewer bugs.

In practice, FastAPI is widely used for microservices, ML model serving (MLOps), and real-time data APIs. It has been adopted by large companies such as Netflix, Uber, and Microsoft, and it is the most popular choice for deploying models as APIs, especially in AI/ML.

💻 Code Example

# FastAPI 기본 서버 예제
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel, Field
from typing import Optional
import uvicorn

app = FastAPI(
    title="KAITRUST API",
    description="FastAPI를 활용한 고성능 API 서버",
    version="1.0.0"
)

# Pydantic 모델 정의 (자동 검증 & 문서화)
class User(BaseModel):
    id: int
    name: str = Field(..., min_length=2, max_length=50)
    email: str
    is_active: bool = True

class UserCreate(BaseModel):
    name: str = Field(..., min_length=2, example="홍길동")
    email: str = Field(..., example="user@example.com")

# 인메모리 데이터베이스 (예시)
users_db: dict[int, User] = {}
next_id = 1

# GET - 사용자 목록 조회
@app.get("/users", response_model=list[User])
async def get_users(
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100)
):
    """모든 사용자를 페이지네이션하여 반환합니다."""
    return list(users_db.values())[skip:skip + limit]

# POST - 새 사용자 생성
@app.post("/users", response_model=User, status_code=201)
async def create_user(user: UserCreate):
    """새 사용자를 생성합니다. 자동 ID 할당."""
    global next_id
    new_user = User(id=next_id, **user.model_dump())
    users_db[next_id] = new_user
    next_id += 1
    return new_user

# GET - 특정 사용자 조회
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int):
    """ID로 특정 사용자를 조회합니다."""
    if user_id not in users_db:
        raise HTTPException(status_code=404, detail="사용자를 찾을 수 없습니다")
    return users_db[user_id]

# 서버 실행: uvicorn main:app --reload
# API 문서: http://localhost:8000/docs (Swagger UI)
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

🗣️ Say It Like This in Practice

💬 In a Meeting
"I think we should build the ML model serving with FastAPI. If we define the input/output schemas with Pydantic, Swagger docs are generated automatically, and async support gives us enough performance for concurrent requests."
💬 In an Interview
"We chose FastAPI because type-hint-based automatic documentation and Pydantic validation give us high development productivity. It outperforms Django REST Framework and supports more modern asynchronous patterns than Flask."
💬 In a code review
"Please specify response_model on this endpoint. The response data is serialized automatically and sensitive fields are filtered out. Also, separating the authentication logic with Depends improves reusability."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Calling synchronous I/O in an async function

Using the regular requests library inside an async def function blocks the event loop. Use an asynchronous HTTP client such as httpx or aiohttp, or wrap the call with run_in_executor.

❌
Ignoring Pydantic model validation

Returning a dict directly skips type validation. Always specify response_model and return a Pydantic model. This prevents sensitive data exposure and keeps the API consistent.

✅
Make use of dependency injection (Depends)

Separate common logic such as authentication, DB sessions, and configuration loading with Depends. It improves code reusability and makes mocking easier in tests. Nested dependencies are also resolved automatically.

🔗 Related Terms

📚 Learn More