0Pricing
FastAPI Backend Development Bootcamp · 강의

FastAPI와 비동기 작업

FastAPI가 비동기 함수를 자연스럽게 처리하는 방식과 효율적인 비차단 코드를 작성하는 방법을 이해합니다.

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

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

FastAPI's Async Foundation

FastAPI is built for speed! It leverages Python's asynchronous features to handle many requests concurrently, especially I/O-bound tasks.

This means your API can stay responsive even when waiting for external resources like databases or other APIs.

Sync vs. Async Endpoints

In FastAPI, you can define two main types of endpoint functions:

  • Synchronous (def): These functions block the event loop while they run. If one request takes long, others might wait.
  • Asynchronous (async def): These functions can 'pause' and let other tasks run while they await an operation (like reading from a database), making your API non-blocking.

Simple Synchronous Endpoint

Here's a standard synchronous endpoint. While simple, if time.sleep() were a real, slow database call, it would block other requests until it completes.

Try running it and observe the delay if you try to make multiple requests quickly.

from fastapi import FastAPI
import uvicorn
import time

app = FastAPI()

@app.get("/sync_hello")
def sync_hello():
    time.sleep(2) # Simulate a blocking I/O operation
    return {"message": "Hello from sync endpoint!"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Defining Asynchronous Endpoints

To make your endpoint non-blocking, use async def. This tells FastAPI (and Python) that this function can be suspended and resumed.

Inside an async def function, you use the await keyword to wait for other asynchronous operations to complete without blocking the entire application.

Your First Async Endpoint

This example uses asyncio.sleep(), which is an asynchronous sleep function. Notice the await keyword before it.

This allows FastAPI to handle other requests while this one 'sleeps', making the server more responsive.

from fastapi import FastAPI
import uvicorn
import asyncio

app = FastAPI()

@app.get("/async_hello")
async def async_hello():
    await asyncio.sleep(2) # Simulate non-blocking I/O
    return {"message": "Hello from async endpoint!"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

When to Go Async

async def shines for I/O-bound operations. These are tasks that spend most of their time waiting for something else to happen, such as:

  • Making requests to external APIs (e.g., httpx).
  • Querying a database (e.g., asyncpg, SQLModel).
  • Reading/writing files from disk.
  • Network communication.

For CPU-bound tasks (heavy calculations), async def doesn't speed up the task itself, but it can help keep the server responsive.

Interacting with Async Libraries

When your FastAPI async def endpoint needs to interact with another asynchronous library (like an async HTTP client or an async database driver), you must use await.

Failing to use await will result in the awaitable object being returned directly, not its resolved result, which is usually not what you want!

Conceptual Async API Call

Imagine fetching data from another service. An async HTTP client allows this without blocking. Here's how it conceptually looks within an async def endpoint:

We simulate network latency with asyncio.sleep to show the non-blocking nature.

from fastapi import FastAPI
import uvicorn
import asyncio

app = FastAPI()

@app.get("/fetch_data")
async def fetch_external_data():
    # In a real app, you'd use an async HTTP client like 'httpx'
    # async with httpx.AsyncClient() as client:
    #     response = await client.get("https://api.example.com/data")
    #     data = response.json()

    await asyncio.sleep(1) # Simulate network latency
    return {"data": "Fetched async data!"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Uvicorn: The Async Engine

FastAPI relies on an ASGI server like Uvicorn. Uvicorn is what actually runs your async def functions efficiently.

  • It manages the Python event loop, which orchestrates when different asynchronous tasks get to run.
  • When an await is encountered, Uvicorn can switch to another ready task, making your API highly concurrent.

This 'context switching' is what allows FastAPI to handle many requests without waiting for each one to finish entirely.

Quick Check: Async Use

You are building a FastAPI endpoint that needs to fetch data from a slow external API (an I/O-bound task). Which of the following is the best way to define this endpoint to ensure your FastAPI application remains responsive?

Recap: Async FastAPI

We've explored how FastAPI harnesses Python's asynchronous features:

  • Use async def for endpoint functions that perform I/O-bound operations.
  • Use await when calling other asynchronous functions or libraries within an async def.
  • This non-blocking approach, powered by Uvicorn and the event loop, allows your FastAPI application to handle many concurrent requests efficiently, leading to highly responsive APIs.

Next, we'll look at how to offload truly long-running or CPU-bound tasks to background processes!

자주 묻는 질문

“FastAPI와 비동기 작업” 강의는 무료인가요?

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

“FastAPI와 비동기 작업”에서 뭘 배우나요?

FastAPI가 비동기 함수를 자연스럽게 처리하는 방식과 효율적인 비차단 코드를 작성하는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“FastAPI와 비동기 작업” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. Python 비동기 프로그래밍 복습
  2. FastAPI와 비동기 작업
  3. 백그라운드 작업 실행
  4. 실시간 통신을 위한 WebSockets
← FastAPI Backend Development Bootcamp(으)로 돌아가기