코드는 적게, 더 빠르게 배송: FastAPI로 API 구축

Towards Data Science | | 📰 뉴스
#api 구축 #fastapi #데이터 검증 #자동 문서화 #파이썬 #하드웨어/반도체 #api 문서화 #python
원문 출처: Towards Data Science · Genesis Park에서 요약 및 분석

요약

FastAPI를 사용하여 경로 작업, Pydantic 모델, 의존성 주입 및 자동 문서화 기능을 마스터하는 방법을 소개합니다. 해당 기사는 개발자가 더 적은 코드를 작성하고 더 빠르게 API를 구축하여 배포할 수 있도록 돕는 실용적인 내용을 담고 있습니다.

본문

FastAPI is built on modern Python features, using standard type hints to provide automatic data validation, serialisation, and interactive API documentation for free. Picking the proper framework depends on your needs. Django is a full-stack framework, and Flask is known for its simplicity. FastAPI, on the other hand, is made for building APIs. It stands out for its speed, ease of use, and ability to reduce repetitive code. So, when should you choose FastAPI for your project? - You’re building an API-centric service. FastAPI is designed from the ground up for this purpose. - You want your code to be your documentation. FastAPI’s automatic docs are a game-changer. - Performance is critical. FastAPI is one of the fastest Python frameworks available. Whether you’re building a small microservice or a complex backend, knowing what FastAPI does best will help you decide if it’s right for you. You’ll get the most from this article if you already know the fundamentals of Python functions, HTTP methods, and JSON. Installing FastAPI You can install FastAPI with just the basics, but it’s best to use the recommended setup. This way, you get everything you need from the start and don’t have to worry about missing dependencies later. Before you begin, it’s a good idea to create and activate a virtual environment. This keeps your project’s dependencies separate and your system tidy. I use UV for this, but you can use any tool you like. Although I usually work on Windows, for this example, I’ll use Ubuntu WSL2 on Windows. I’ll also run the code in a Jupyter Notebook, which means adding a bit of extra code to handle Jupyter’s event loop, since it can conflict with FastAPI’s async features. tom@tpr-desktop:~$ uv init fastapi Initialized project `fastapi` at `/home/tom/fastapi` tom@tpr-desktop:~$ cd fastapi tom@tpr-desktop:~/fastapi$ uv venv Using CPython 3.13.0 Creating virtual environment at: .venv Activate with: source .venv/bin/activate tom@tpr-desktop:~/fastapi$ source .venv/bin/activate (fastapi) tom@tpr-desktop:~/fastapi$ To get the full FastAPI experience, install it with the [standard] extras. This includes the FastAPI command-line tool and the Uvicorn ASGI server, which you’ll need to run your app. (fastapi) tom@tpr-desktop:~/fastapi$ uv pip install jupyter "fastapi[standard]" Resolved 124 packages in 2.88s Prepared 26 packages in 1.06s Installed 124 packages in 80ms + annotated-types==0.7.0 + anyio==4.11.0 + argon2-cffi==25.1.0 ... ... ... + webencodings==0.5.1 + websocket-client==1.8.0 + websockets==15.0.1 + widgetsnbextension==4.0.14 (fastapi) tom@tpr-desktop:~/fastapi$ To verify that everything is okay, start up a Jupyter Notebook and type in the following code. You should receive a version number in return. Depending on when you run this code, your version number will likely differ from mine. import fastapi print(fastapi.__version__) # My Output 0.129.0 We’re now ready to build some applications. Example 1: Hello World Creating a basic FastAPI application takes just a few lines of code. We’ll start with a simple “Hello World” message to illustrate the framework’s core mechanics. Don’t worry, our apps will become more useful soon. Type the following code into a notebook cell. import nest_asyncio import uvicorn from fastapi import FastAPI # Patch asyncio to allow nested use (needed in Jupyter/Colab) nest_asyncio.apply() app = FastAPI() @app.get("/") def home(): return {"message": "Hello, World!"} # Use Config + Server instead of uvicorn.run() config = uvicorn.Config(app=app, host="127.0.0.1", port=8000, log_level="info") server = uvicorn.Server(config) await server.serve() As mentioned previously, there’s a bit of extra scaffolding required in this code because I’m running in a Notebook environment, which you wouldn’t usually need if running as a stand-alone Python module. Still, this small example reveals a great deal already. You import FastAPI, create an app instance, and use a decorator (@app.get(“/”)) to tell FastAPI that the home() function should handle GET requests to the root path. The function returns a simple text string. When you run the code above, you should see output similar to this. INFO: Started server process [28755] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) If you now click on the URL in the above output, you should see something like this. Now, let’s build something more useful. Example 2: A Functional To-Do List Real-world APIs need to manage data. Let’s expand our code to create a simple in-memory To-Do list API that will allow full CRUD operations. This will showcase path parameters, request bodies, and data validation. from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List, Optional import uvicorn import nest_asyncio import threading app = FastAPI() # --- Pydantic Models for Data Validation --- class TodoItem(BaseModel): id: int description: str

Genesis Park 편집팀이 AI를 활용하여 작성한 분석입니다. 원문은 출처 링크를 통해 확인할 수 있습니다.

공유

관련 저널 읽기

전체 보기 →