본문 바로가기
Data

[FastAPI] FastAPI에서 POST 요청 시 Content-Type 설정

by clolee 2025. 5. 7.

✅ FastAPI에서 POST 요청 시 Content-Type: application/json이 필요한 이유

📌 주제

FastAPI에 JSON 데이터를 POST할 때 Content-Type 헤더를 설정하지 않으면 발생하는 오류와 그 해결 방법


🧩 문제 상황

FastAPI로 만든 다음과 같은 API가 있다고 가정합니다:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class InDataset(BaseModel):
    targetYear: int

@app.post("/predictSumQty")
async def predict_tf(x: InDataset):
    response = totalQtySum(x.targetYear)
    return {"prediction": response}

Postman에서 다음 JSON을 보냈는데 오류가 발생합니다:

{
  "targetYear": 2015
}

🚨 에러 메시지

500 Internal Server Error 또는 422 Unprocessable Entity
sqlalchemy.exc.PendingRollbackError: ...

이는 FastAPI가 JSON을 제대로 파싱하지 못해 내부 로직이 잘못 작동했기 때문입니다.


🎯 원인

Content-Type: application/json 헤더가 누락되어,
FastAPI가 요청 본문을 JSON이 아닌 다른 형식으로 해석하려 하기 때문입니다.

 

FastAPI는 pydantic 모델을 사용하여 JSON body를 자동 파싱합니다.
하지만 헤더가 없으면 body를 JSON으로 인식하지 못하고 에러가 발생합니다.


✅ 해결 방법

🔧 Postman 설정 방법

  1. Headers 탭
  2. Key: Content-Type Value: application/json
  3. Body 탭
    • raw 선택
    • JSON 형식 선택
    • 아래와 같이 작성:
    • { "targetYear": 2015 }

🛠️ 혹시 x-www-form-urlencoded 방식으로 받으려면?

FastAPI는 기본적으로 JSON을 기대하므로, 폼 데이터를 받으려면 이렇게 수정해야 합니다:

from fastapi import Form

@app.post("/predictSumQty")
async def predict_tf(targetYear: int = Form(...)):
    return {"prediction": totalQtySum(targetYear)}

하지만 실무에서는 JSON 방식이 더 명확하고 유연하기 때문에 pydantic + JSON 조합을 추천합니다.


🧾 결론

  • FastAPI에서 pydantic 모델로 POST 요청 받을 때는 반드시
    👉 Content-Type: application/json 헤더를 설정해야 함
  • Postman이나 클라이언트에서 설정이 없으면 422 또는 500 오류가 발생할 수 있음
  • 실무에서는 JSON 포맷 사용 + 명시적 헤더 설정이 표준

 

'Data' 카테고리의 다른 글

[Python] ETL(Extract, Transform, Load) 각 단계의 의미  (0) 2025.05.09
[Kaggle] kaggle.json 인증키 발급  (0) 2025.05.02

댓글