0Pricing
FastAPI Backend Development Bootcamp · 강의

응답 모델 및 상태 코드

명시적인 응답 모델을 정의하고 다양한 API 작업에 적절한 HTTP 상태 코드를 설정하는 방법을 배웁니다.

응답 모델 및 상태 코드은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

API Responses: The Basics

When you make a request to an API, the server sends back a response. This response isn't just data; it also includes important information about the request's outcome.

FastAPI makes it easy to return data, usually as JSON. But we can make our APIs even better by being explicit about what data to expect and what happened.

Why Use Response Models?

Response models define the exact structure of the data your API will send back. This is crucial for several reasons:

  • Data Consistency: Ensures your API always returns data in a predictable format.
  • Automatic Docs: FastAPI automatically generates OpenAPI documentation showing the expected response structure.
  • Data Validation: FastAPI can validate the outgoing data against your model, catching errors before sending.

Defining a Simple Response Model

We use Pydantic models to define response structures. Then, we tell FastAPI which model to use with the response_model parameter in our endpoint decorator.

Try running this example and check the /docs endpoint!

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    name: str
    price: float
    is_available: bool = True

@app.get("/products/single", response_model=Product)
def get_single_product():
    return {"name": "Coffee Mug", "price": 9.99, "is_available": True}

# To run: uvicorn main:app --reload

Returning Lists with Response Models

What if your endpoint returns a list of items? You can specify this in your response_model by using Python's List type from the typing module.

This tells FastAPI to expect a list where each item matches your Pydantic model.

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Book(BaseModel):
    title: str
    author: str

@app.get("/books", response_model=List[Book])
def get_all_books():
    return [
        {"title": "The Hobbit", "author": "J.R.R. Tolkien"},
        {"title": "1984", "author": "George Orwell"}
    ]

# To run: uvicorn main:app --reload

Understanding HTTP Status Codes

Beyond the data, every API response includes an HTTP Status Code. This three-digit number tells the client about the outcome of their request.

  • 2xx Success: Request was successfully received, understood, and accepted. (e.g., 200 OK, 201 Created)
  • 4xx Client Error: The client made an error. (e.g., 400 Bad Request, 404 Not Found)
  • 5xx Server Error: The server failed to fulfill an apparently valid request. (e.g., 500 Internal Server Error)

FastAPI's Default Status Codes

FastAPI automatically assigns default status codes based on the HTTP method:

  • GET: 200 OK
  • POST: 200 OK (but often 201 Created is better)
  • PUT/DELETE: 200 OK

While these defaults work, explicitly setting status codes makes your API more precise and user-friendly.

Setting Custom Success Codes (201)

For operations that create a new resource (like a POST request), returning a 201 Created status code is best practice. You can specify this directly in your path operation decorator.

Run this and observe the network response code!

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()

class NewItem(BaseModel):
    name: str
    description: str | None = None

@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(item: NewItem):
    # Imagine saving 'item' to a database here
    return {"message": "Item created successfully", "item": item}

# To run: uvicorn main:app --reload

Handling Errors with HTTPException (404)

When a requested resource isn't found, you should return a 404 Not Found status. FastAPI provides HTTPException to raise these errors easily.

This stops execution and returns a standard JSON error response.

from fastapi import FastAPI, HTTPException, status

app = FastAPI()

fake_items_db = {"foo": {"name": "Foo"}, "bar": {"name": "Bar"}}

@app.get("/items/{item_id}")
def read_item(item_id: str):
    if item_id not in fake_items_db:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
    return fake_items_db[item_id]

# To run: uvicorn main:app --reload

Combining Models & Status Codes

You'll often use both response models and custom status codes together. For example, a successful update might return a 200 OK with the updated resource, while a failed update might return a 400 Bad Request.

This creates robust and predictable API behavior.

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()

class UserOut(BaseModel):
    id: int
    username: str

@app.put("/users/{user_id}", response_model=UserOut, status_code=status.HTTP_200_OK)
def update_user(user_id: int, new_username: str):
    # Imagine updating user in DB
    if user_id == 1:
        return {"id": user_id, "username": new_username}
    return {"id": user_id, "username": "default_user"}

# To run: uvicorn main:app --reload

Quick Check: Status Codes

A client sends a POST request to create a new user. The server successfully processes the request and saves the user data. Which HTTP status code is the most appropriate to return?

Recap: Clear Responses

In this lesson, you learned how to make your FastAPI responses clear and predictable. We covered:

  • Defining response models with Pydantic for consistent data and automatic documentation.
  • Understanding and explicitly setting HTTP status codes like 201 Created or handling errors with HTTPException for 404 Not Found.

These practices greatly improve the usability and robustness of your API.

자주 묻는 질문

“응답 모델 및 상태 코드” 강의는 무료인가요?

네 — “응답 모델 및 상태 코드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“응답 모델 및 상태 코드”에서 뭘 배우나요?

명시적인 응답 모델을 정의하고 다양한 API 작업에 적절한 HTTP 상태 코드를 설정하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“응답 모델 및 상태 코드” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 요청 본문을 위한 Pydantic 모델
  2. 응답 모델 및 상태 코드
  3. 폼 데이터 및 파일 업로드
  4. 헤더, 쿠키 및 사용자 지정 응답
← FastAPI Backend Development Bootcamp(으)로 돌아가기