Skip to content

첫 FastAPI 애플리케이션

라이브러리

fastapi
pydantic

# 파이썬 ASGI 서버 (장고 등도 구동 가능)
uvicorn[standard]

# 세션 라이브러리

# JWT 생성/검증 등 보안 토큰 처리
python-jose[cryptography]

# .env 환경변수 로딩
python-dotenv

# ----------------------------------
# 아래 기능들은 장고에서는 기본에서 지원합니다.
# ----------------------------------

# 비밀번호 해싱
passlib[bcrypt]

# 폼 데이터에서 파일 업로드 처리를 지원
python-multipart

# 템플릿 엔진
jinja2

# ORM
sqlalchemy

Note

requirements.txt 파일이 전통적인 파이썬 의존 라이브러리 명세 파일이며, 요즘 pyproject.toml 포맷도 인기

FastAPI 웹 애플리케이션

entry.py
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()

@app.get("/")
def index():
    return {"Hello": "World!"}  # JSON 응답

@app.get("/articles/100/")
def article_detail():
    return {"id": 100, "title": "아티클 #100", "content": "..."}

@app.get("/posts/{post_id}/")
def post_detail(post_id: int):

    # 데이터베이스에서 지정 레코드가 없다면, 상태코드 404 응답
    if not (1 <= post_id <= 100):
        raise HTTPException(
            status_code=404,
            detail=f"post_id는 1 이상 100 이하여야 합니다. 입력값: {post_id}"
        )

    return {"id": post_id, "title": f"포스팅 #{post_id}", "content": "..."}

서버 구동 및 접속 확인

FastAPI에서는 FastAPI CLI를 지원합니다.

fastapi dev entry.py  # 개발용
fastapi run entry.py  # 실서비스용

내부에서 uvicorn 명령을 사용하며, 이 외에도 다양한 파이썬 웹 서버를 통해 직접 구동할 수 있습니다.

  • uvicorn : 경량 ASGI 서버
  • Gunicorn + Uvicorn : Gunicorn의 프로세스 관리 기능 + Uvicorn의 성능 결합 (실서비스 용)
    • gunicorn main:app -k uvicorn.workers.UvicornWorker -w 4
  • Hypercorn : http/2 지원 및 다양한 이벤트 루프 지원
$ fastapi dev entry.py

   FastAPI   Starting development server 🚀

             Searching for package file structure from directories with __init__.py files
             Importing from /Users/allieus/Temp/test-fastapi

    module   🐍 entry.py

      code   Importing the FastAPI app object from the module with the following code:

             from entry import app

       app   Using import string: entry:app

    server   Server started at http://127.0.0.1:8000
    server   Documentation at http://127.0.0.1:8000/docs

       tip   Running in development mode, for production use: fastapi run

             Logs:

      INFO   Will watch for changes in these directories: ['/Users/allieus/Temp/test-fastapi']
      INFO   Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
      INFO   Started reloader process [31129] using WatchFiles
      INFO   Started server process [31131]
      INFO   Waiting for application startup.
      INFO   Application startup complete.
$ uvicorn entry:app
INFO:     Started server process [54855]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
항상 --help 옵션을 살펴보세요.

어떤 기능들이 제공되는 지 가장 빠르게 파악할 수 있는 방법입니다. 이는 Google, GPT 조차도 설명해주지 않습니다.

$ uvicorn entry:app --help
Usage: uvicorn [OPTIONS] APP

Options:
  --host TEXT                     Bind socket to this host.  [default:
                                  127.0.0.1]
  --port INTEGER                  Bind socket to this port. If 0, an available
                                  port will be picked.  [default: 8000]
  --reload                        Enable auto-reload.
  --reload-dir PATH               Set reload directories explicitly, instead
                                  of using the current working directory.
  --reload-include TEXT           Set glob patterns to include while watching
                                  for files. Includes '*.py' by default; these
                                  defaults can be overridden with `--reload-
                                  exclude`. This option has no effect unless
                                  watchfiles is installed.
  --reload-exclude TEXT           Set glob patterns to exclude while watching
                                  for files. Includes '.*, .py[cod], .sw.*,
                                  ~*' by default; these defaults can be
                                  overridden with `--reload-include`. This
                                  option has no effect unless watchfiles is
                                  installed.
  --reload-delay FLOAT            Delay between previous and next check if
                                  application needs to be. Defaults to 0.25s.
                                  [default: 0.25]
  --workers INTEGER               Number of worker processes. Defaults to the
                                  $WEB_CONCURRENCY environment variable if
                                  available, or 1. Not valid with --reload.
  --loop [auto|asyncio|uvloop]    Event loop implementation.  [default: auto]
  --http [auto|h11|httptools]     HTTP protocol implementation.  [default:
                                  auto]
  --ws [auto|none|websockets|wsproto]
                                  WebSocket protocol implementation.
                                  [default: auto]
  --ws-max-size INTEGER           WebSocket max size message in bytes
                                  [default: 16777216]
  --ws-max-queue INTEGER          The maximum length of the WebSocket message
                                  queue.  [default: 32]
  --ws-ping-interval FLOAT        WebSocket ping interval in seconds.
                                  [default: 20.0]
  --ws-ping-timeout FLOAT         WebSocket ping timeout in seconds.
                                  [default: 20.0]
  --ws-per-message-deflate BOOLEAN
                                  WebSocket per-message-deflate compression
                                  [default: True]
  --lifespan [auto|on|off]        Lifespan implementation.  [default: auto]
  --interface [auto|asgi3|asgi2|wsgi]
                                  Select ASGI3, ASGI2, or WSGI as the
                                  application interface.  [default: auto]
  --env-file PATH                 Environment configuration file.
  --log-config PATH               Logging configuration file. Supported
                                  formats: .ini, .json, .yaml.
  --log-level [critical|error|warning|info|debug|trace]
                                  Log level. [default: info]
  --access-log / --no-access-log  Enable/Disable access log.
  --use-colors / --no-use-colors  Enable/Disable colorized logging.
  --proxy-headers / --no-proxy-headers
                                  Enable/Disable X-Forwarded-Proto,
                                  X-Forwarded-For, X-Forwarded-Port to
                                  populate remote address info.
  --server-header / --no-server-header
                                  Enable/Disable default Server header.
  --date-header / --no-date-header
                                  Enable/Disable default Date header.
  --forwarded-allow-ips TEXT      Comma separated list of IP Addresses, IP
                                  Networks, or literals (e.g. UNIX Socket
                                  path) to trust with proxy headers. Defaults
                                  to the $FORWARDED_ALLOW_IPS environment
                                  variable if available, or '127.0.0.1'. The
                                  literal '*' means trust everything.
  --root-path TEXT                Set the ASGI 'root_path' for applications
                                  submounted below a given URL path.
  --limit-concurrency INTEGER     Maximum number of concurrent connections or
                                  tasks to allow, before issuing HTTP 503
                                  responses.
  --backlog INTEGER               Maximum number of connections to hold in
                                  backlog
  --limit-max-requests INTEGER    Maximum number of requests to service before
                                  terminating the process.
  --timeout-keep-alive INTEGER    Close Keep-Alive connections if no new data
                                  is received within this timeout.  [default:
                                  5]
  --timeout-graceful-shutdown INTEGER
                                  Maximum number of seconds to wait for
                                  graceful shutdown.
  --ssl-keyfile TEXT              SSL key file
  --ssl-certfile TEXT             SSL certificate file
  --ssl-keyfile-password TEXT     SSL keyfile password
  --ssl-version INTEGER           SSL version to use (see stdlib ssl module's)
                                  [default: 17]
  --ssl-cert-reqs INTEGER         Whether client certificate is required (see
                                  stdlib ssl module's)  [default: 0]
  --ssl-ca-certs TEXT             CA certificates file
  --ssl-ciphers TEXT              Ciphers to use (see stdlib ssl module's)
                                  [default: TLSv1]
  --header TEXT                   Specify custom default HTTP response headers
                                  as a Name:Value pair
  --version                       Display the uvicorn version and exit.
  --app-dir TEXT                  Look for APP in the specified directory, by
                                  adding this to the PYTHONPATH. Defaults to
                                  the current working directory.  [default:
                                  ""]
  --h11-max-incomplete-event-size INTEGER
                                  For h11, the maximum number of bytes to
                                  buffer of an incomplete event.
  --factory                       Treat APP as an application factory, i.e. a
                                  () -> <ASGI app> callable.
  --help                          Show this message and exit.

Comments