요청 및 응답 모델

FastAPI로 AI 프로덕션 배포하기

Matt Eckerle

Software and Data Engineering Leader

API의 요청 및 응답 구조

요청 구조
  • 클라이언트가 API로 전송하는 데이터
  • 주로 포함되는 항목:
    • HTTP 메서드 (GET, POST 등)
    • 헤더
    • 쿼리 파라미터
    • 요청 본문

http://localhost:8000/users/? [email protected]

  • :8000: 포트 번호. FastAPI는 기본적으로 8000을 사용합니다.
  • /users/: 접근하는 엔드포인트의 경로입니다.
  • ?: 쿼리 파라미터의 시작을 나타냅니다.
  • `[email protected]`: 쿼리 파라미터. 이메일 주소를 엔드포인트에 전달합니다.
FastAPI로 AI 프로덕션 배포하기

응답 구조

  • API가 클라이언트에 반환하는 데이터
    • 사용자 정보를 포함한 JSON 응답 페이로드
  • 주로 포함되는 항목:
    • 상태 코드 (200 OK, 404 Not Found 등)
    • 헤더
    • 응답 본문 (요청 데이터 또는 작업 결과)
HTTP/1.1 200 OK
date: Fri, 18 Oct 2024 12:34:56 GMT
server: uvicorn
content-length: 76
content-type: application/json

{
  "username": "johndoe",
  "email": "[email protected]",
  "age": 30
}
FastAPI로 AI 프로덕션 배포하기

Pydantic 모델

  • User 생성
  • Pydantic 사용
from pydantic import BaseModel
class User(BaseModel):
    username: str
    email: str
    age: int
  • BaseModel 상속
  • 타입 어노테이션으로 속성 정의
  • 타입 기반 자동 유효성 검사
FastAPI로 AI 프로덕션 배포하기

유효성 검사 오류

from pydantic import ValidationError
try:
    invalid_user = User(username="john_doe", email="[email protected]", 
                        age="thirty")
    print("Invalid User:", invalid_user)
except ValidationError as e:
    print("Validation Error:", e)
Validation Error: 1 validation error for User age
Input should be a valid integer, unable to parse string as an integer 
[type=int_parsing, input_value='thirty', input_type=str]
FastAPI로 AI 프로덕션 배포하기

FastAPI에서 Pydantic 모델 사용

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class User(BaseModel): username: str email: str age: int
@app.post("/users", response_model=User)
async def create_user(user: User): return user
  • response_model로 모델 사용
  • 매개변수 타입 힌트로 모델 사용
  • 자동 요청 유효성 검사
  • 요청/응답 직렬화 및 역직렬화
  • API 문서 자동 생성
FastAPI로 AI 프로덕션 배포하기

요청 및 응답 형식

curl -X 'POST' \
  'http://localhost:8000/users/' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
  }'

 

{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
}
FastAPI로 AI 프로덕션 배포하기

연습해 봅시다!

FastAPI로 AI 프로덕션 배포하기

Preparing Video For Download...