0Pricing
FastAPI Backend Development Bootcamp · 강의

FastAPI에서 WebSockets 구현

FastAPI 애플리케이션에 WebSocket 엔드포인트를 추가하고 연결을 처리하는 방법을 배웁니다.

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

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

Real-time with FastAPI WebSockets

Welcome to implementing WebSockets with FastAPI! WebSockets provide a persistent, full-duplex communication channel between a client and a server.

  • Full-duplex: Both client and server can send and receive messages simultaneously.
  • Real-time: Ideal for applications needing instant updates, like chat, live dashboards, or gaming.

FastAPI has excellent built-in support for WebSockets, leveraging Python's async/await features.

Defining a WebSocket Endpoint

Just like HTTP endpoints, you define WebSocket endpoints using a decorator. Instead of @app.get() or @app.post(), you use @app.websocket().

Your endpoint function must be async def and accept a websocket: WebSocket parameter. This WebSocket object is your primary tool for interaction.

The first step inside your function is always to await websocket.accept() to establish the connection.

Your First WebSocket Connection

Let's create our first WebSocket endpoint. This simple example accepts a connection, sends a welcome message, and then closes the connection.

Notice the @app.websocket("/ws") decorator and the async def function, which are key for WebSocket handling.

Try running this example and observe the connection:

from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_text("Welcome! Connection established.")
    await websocket.close()

Handling WebSocket Disconnections

WebSocket connections can be interrupted for various reasons (client closes tab, network error). It's crucial to handle these disconnections gracefully.

FastAPI raises a WebSocketDisconnect exception when a client disconnects. You can catch this exception to perform cleanup tasks, like removing the client from a list of active connections.

Wrap your WebSocket communication logic in a try...except WebSocketDisconnect block.

Receiving Messages from Clients

Once connected, your server can receive messages from the client. The WebSocket object provides methods for this:

  • await websocket.receive_text(): For receiving string data.
  • await websocket.receive_bytes(): For receiving binary data.
  • await websocket.receive_json(): For receiving JSON data (requires python-multipart).

These operations are asynchronous, so always use await.

Echoing Client Messages Back

This example demonstrates a simple 'echo' server. It accepts a connection, then continuously receives messages from the client and sends them back.

The while True loop keeps the connection open, and the try...except WebSocketDisconnect handles when the client leaves.

from fastapi import FastAPI, WebSocket, WebSocketDisconnect

app = FastAPI()

@app.websocket("/ws/echo")
async def websocket_echo(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            data = await websocket.receive_text()
            print(f"Received from client: {data}")
            await websocket.send_text(f"Server echoed: {data}")
    except WebSocketDisconnect:
        print("Client disconnected.")

Sending Messages to Clients

Similarly, your server can send messages to the client. The WebSocket object offers:

  • await websocket.send_text("your message"): To send string data.
  • await websocket.send_bytes(b"your bytes"): To send binary data.
  • await websocket.send_json({"key": "value"}): To send JSON data.

Remember to await these calls. It's common to send a response right after receiving a message.

Working with JSON Data

For structured data, sending and receiving JSON is preferred. FastAPI's WebSocket object handles serialization/deserialization for you.

  • Sending: Pass a Python dict to send_json().
  • Receiving: receive_json() returns a Python dict.

This simplifies data exchange compared to manually parsing strings.

Simple Connection Manager

For applications with multiple clients, you'll need to manage active connections. A common pattern is to use a class to keep track of all connected WebSocket objects.

This manager can then be used to add/remove connections and send messages to specific clients or broadcast to all.

from fastapi import WebSocket

class ConnectionManager:
    def __init__(self):
        self.active_connections: list[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

# In a real app, you'd integrate 'manager' into your FastAPI endpoint
manager = ConnectionManager()

WebSocket Interaction Check

You've learned the basics of setting up and interacting with WebSocket connections in FastAPI.

Let's check your understanding of accepting new connections.

Recap: Implementing WebSockets

You've successfully learned how to implement WebSockets in FastAPI!

  • Use @app.websocket() to define endpoints.
  • Always await websocket.accept() to establish the connection.
  • Handle disconnections with try...except WebSocketDisconnect.
  • Use await websocket.receive_text() and await websocket.send_text() for communication.
  • For structured data, send_json() and receive_json() are your friends.

Next, you'll build a real-time chat application to put these concepts into practice!

자주 묻는 질문

“FastAPI에서 WebSockets 구현” 강의는 무료인가요?

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

“FastAPI에서 WebSockets 구현”에서 뭘 배우나요?

FastAPI 애플리케이션에 WebSocket 엔드포인트를 추가하고 연결을 처리하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“FastAPI에서 WebSockets 구현” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. WebSocket 프로토콜 기초
  2. FastAPI에서 WebSockets 구현
  3. 실시간 채팅 애플리케이션 만들기
  4. Pub/Sub 백플레인으로 WebSockets 확장하기
← FastAPI Backend Development Bootcamp(으)로 돌아가기