[TIL] Day 82 FastAPI

현서·2026년 3월 25일

[TIL] Flutter 9기

목록 보기
94/102

FastAPI


FastAPI란?

Python 기반의 빠르고 가벼운 웹 프레임워크.
REST API 서버를 빠르게 만들 수 있고, 자동으로 API 문서도 생성해줌

  • 속도: Node.js, Go에 버금가는 성능
  • 자동 문서화: /docs 경로에서 Swagger UI 바로 확인 가능
  • 타입 힌트 기반: Python 타입 힌트로 요청/응답 데이터 검증

기본 구조

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI"}
  • @app.get(), @app.post() — HTTP 메서드에 대응하는 데코레이터
  • 함수 반환값이 자동으로 JSON 응답으로 변환됨

실행

pip install fastapi uvicorn
uvicorn main:app --reload   # --reload: 코드 변경 시 자동 재시작

서버 실행 후 http://127.0.0.1:8000/docs 에서 자동 생성된 API 문서 확인 가능.


비동기 처리 (async/await)

FastAPI는 비동기를 기본으로 지원함.
DB 조회, 외부 API 호출처럼 기다리는 작업은 async로 처리하면 다른 요청을 블로킹하지 않음.

import asyncio

@app.get("/slow")
async def slow_endpoint():
    await asyncio.sleep(2)   # 2초 기다리는 동안 다른 요청 처리 가능
    return {"message": "done"}
  • async def — 비동기 함수 선언
  • await — 비동기 작업이 끝날 때까지 대기 (다른 요청은 계속 처리)
  • 단순 계산만 하는 함수는 그냥 def도 무방

Flutter 연동

Flutter에서 FastAPI 서버로 HTTP 요청을 보내는 기본 패턴.

FastAPI 서버 측

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Message(BaseModel):
    text: str

@app.post("/echo")
async def echo(message: Message):
    return {"reply": f"받은 메시지: {message.text}"}

Flutter 클라이언트 측

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<void> sendMessage() async {
  final response = await http.post(
    Uri.parse('http://127.0.0.1:8000/echo'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({'text': '안녕하세요'}),
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    print(data['reply']);
  }
}

로컬 테스트 시 Android 에뮬레이터는 10.0.2.2, iOS 시뮬레이터는 127.0.0.1 사용


느낀 점

Firebase Functions는 JS/TS 기반인데, FastAPI는 Python이라 AI 모델이나 데이터 처리 붙일 때 훨씬 자연스럽겠다는 생각이 들었다.
Flutter는 클라이언트, FastAPI는 서버 역할로 조합하면 풀스택 구성도 가능하다는 게 흥미로웠듬

0개의 댓글