개요
FastAPI는 표준 타입 힌트를 기반으로 API를 구축하는 현대적인 고성능 Python 웹 프레임워크입니다. OpenAPI와 JSON Schema를 통해 대화형 문서를 자동으로 생성하고, Pydantic을 활용해 데이터 검증을 수행하며, Starlette를 기반으로 비동기를 지원합니다. 배우기 쉽고 개발 효율이 높아 프로덕션 환경에 바로 적용할 수 있습니다.
README 미리보기
\n \n\n\n FastAPI framework, high performance, easy to learn, fast to code, ready for production\n\n\n\n \n\n\n \n\n\n \n\n\n \n\n\n\n---\n\n**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com)\n\n**Source Code**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)\n\n---\n\nFastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.\n\nThe key features are:\n\n* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).\n* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *\n* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *\n* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.\n* **Easy**: Designed to be easy to use and learn. Less time reading docs.\n* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.\n* **Robust**: Get production-ready code. With automatic interactive documentation.\n* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (previously known as Swagger) and [JSON Schema](https://json-schema.org/).\n\n* estimation based on tests conducted by an internal development team, building production applications.\n\n## Sponsors\n\n\n### Keystone Sponsor\n\n\n\n### Gold Sponsors\n\n\n\n\n\n\n\n\n\n### Silver Sponsors\n\n\n\n\n\n\n\n\n\n[Other sponsors](https://fastapi.tiangolo.com/fastapi-people/#sponsors)\n\n## Opinions\n\n\n\n\n\n"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"\n\nKabir Khan - Microsoft (ref)\n\n---\
FAQ (4)
문제 해결I'm not aware of a documented bug specific to FastAPI 0.142.0 involving `OTEL_EXPORTER_OTLP_ENDPOINT` — that version may be newer than my reliable knowledge, so I can't confirm a version-specific regression. However, I can explain what's almost certainly happening, because this class of failure is common and well understood.
## Why this happens
FastAPI itself never reads `OTEL_EXPORTER_OTLP_ENDPOINT`. The failure comes from the OpenTelemetry SDK/instrumentation layer (e.g., `opentelemetry-instrumentation-fastapi`, `opentelemetry-sdk`, or auto-instrumentation via `opentelemetry-instrument`). When that env var is set, the OTel SDK initializes OTLP exporters at startup, and that's where things break. The usual culprits:
1. **Malformed endpoint URL.** The base `OTEL_EXPORTER_OTLP_ENDPOINT` must include a scheme and *no* signal path:
- gRPC: `http://localhost:4317`
- HTTP/protobuf: `http://localhost:4318`
Common mistakes: omitting `http://`, adding a trailing slash, or appending `/v1/traces` yourself (the HTTP exporter appends signal paths automatically, so you end up with `/v1/traces/v1/traces` and 404s).
2. **Version incompatibility.** `opentelemetry-instrumentation-fastapi` has broken multiple times against newer FastAPI/Starlette releases due to internal API changes (middleware handling, `is_coroutine_callable`, etc.). A brand-new FastAPI version may not yet be supported by your installed OTel packages.
3. **Wrong exporter for the port/protocol.** Setting an HTTP-style endpoint while only `opentelemetry-exporter-otlp-proto-grpc` is installed (or vice versa).
## How to diagnose
- Confirm OTel is the cause by starting with:
```bash
OTEL_SDK_DISABLED=true uvicorn main:app
```
If it starts fine, the problem is in the OTel layer, not FastAPI.
- Look at the actual traceback — the failing package will be `opentelemetry-*`, not `fastapi`.
- Enable debug output: `OTEL_LOG_LEVEL=debug`
## Fixes
1. Correct the endpoint format (scheme, correct port, no path).
2. Upgrade all OpenTelemetry packages together to versions supporting your FastAPI/Starlette:
```bash
pip install -U opentelemetry-sdk opentelemetry-instrumentation-fastapi opentelemetry-exporter-otlp
```
If no compatible release exists yet, pin FastAPI to the last working version until the instrumentation catches up.
3. If the collector simply isn't reachable, note that exporters normally retry in the background rather than crash — a hard startup crash almost always indicates a config or version issue, not connectivity.
If you can share the exact traceback, I can pinpoint which of these applies.
이는 FastAPI 0.142.0의 버그입니다: OTEL_EXPORTER_OTLP_ENDPOINT 환경 변수가 설정되어 있지만(호스팅 플랫폼에서 흔한 경우) OpenTelemetry extra가 설치되어 있지 않으면, 앱이 시작 시 'Automatic OpenTelemetry export requires fastapi[opentelemetry]' 오류와 함께 비정상 종료됩니다. 해결 방법: FastAPI 0.142.2 이상으로 업그레이드하면 이 문제가 해결됩니다(PR #16418). 0.142.0을 계속 사용해야 하는 경우 대체 해결 방법은 다음과 같습니다: (1) pip install fastapi[opentelemetry] 또는 fastapi[standard]로 extra를 설치하거나, (2) FastAPI()에 telemetry={'auto_configure': False}를 전달하여 자동 구성을 비활성화하거나, (3) FastAPI 0.141.0으로 다운그레이드하는 것입니다.
문제 해결FastAPI generate_unique_id_function에서 "Object of type 'APIRoute' has no attribute 'tags'" 타입 체커 오류를 수정하는 방법은?
이것은 FastAPI 0.137.0에서 발생한 타입 어노테이션 회귀(regression)로(PR #15745에서 도입됨), APIRoute가 클래스 수준의 tags 어노테이션을 잃어버려, 커스텀 generate_unique_id_function 내부에서 타입 체커(ty, Pyright strict)가 route.tags에 대해 unresolved-attribute 오류를 보고합니다 — 코드가 런타임에는 정상적으로 동작함에도 불구하고 말입니다. 해결 방법: 해당 어노테이션을 복원한 FastAPI 0.137.1 이상으로 업그레이드하세요(PR #15765):
pip install -U "fastapi>=0.137.1"
그러면 문서에 나온 패턴이 올바르게 타입 검사를 통과합니다:
from fastapi import FastAPI
from fastapi.routing import APIRoute
def custom_generate_unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}-{route.name}"
app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
임시로 0.137.0 버전을 유지해야 한다면, route.tags 라인에 # type: ignore[attr-defined] 주석을 달아 오류를 무시하거나, getattr(route, "tags", [])를 통해 접근하세요.
문제 해결라우터가 포함된 후 FastAPI APIRouter.routes에 직접 추가된 라우트가 404를 반환하고(제거된 라우트는 여전히 응답하는) 이유는 무엇인가요?
FastAPI는 (lazy router-inclusion 재작성 이후, #15745) 포함된 각 라우터의 해석된 라우트를 내부 버전 카운터(APIRouter._routes_version)를 키로 하여 캐시합니다. append(), remove(), clear(), 슬라이스 할당 또는 재할당으로 router.routes를 직접 변경하면 이 카운터가 절대 증가하지 않으므로, 부모 라우터는 오래된 캐시 목록을 계속 제공하게 됩니다: 새 라우트는 404를 반환하고, 삭제된 라우트는 '유령(ghost)' 라우트로서 계속 응답합니다.
우회 방법:
1. 캐시를 올바르게 무효화하는, 추적되는 공식 메서드를 통해서만 라우트를 변경하세요:
# child.routes.append(APIRoute("/child2", handler, methods=["GET"])) 대신
child.add_api_route("/child2", handler, methods=["GET"])
# 또는: child.add_route(...), child.include_router(...)2.
router.routes를 직접 변경해야만 하는 경우(예: 라우트를 제거하기 위해 app.router.routes = [...]를 사용하는 경우), 직후에 캐시를 수동으로 무효화하세요:child.routes.append(new_route)
child._mark_routes_changed() # 비공개(private) API이며 향후 릴리스에서 변경될 수 있음3. 캐시는 첫 번째 디스패치 시에만 생성되므로, 라우터가 포함되기 전과 앱이 첫 번째 요청을 처리하기 전에 모든 직접 변경을 수행하세요.
.routes가 변경을 인식하도록 만드는 근본적인 수정은 fastapi issue #16301에서 논의되고 있습니다.
문제 해결FastAPI iter_route_contexts()가 WebSocket 라우트에 대해 빈 경로를 반환하는 이유는 무엇인가요?
이것은 FastAPI 0.137.2+에서 확인된 버그입니다(0.141.1에서도 여전히 존재합니다). iter_route_contexts()는 HTTP 라우트에는 include_router() prefix를 적용하지만, APIWebSocketRoute에 대해서는 ctx.path == ""를 yield하며, ctx.route.path에는 prefix가 붙지 않은 경로만 들어 있습니다. 아직 수정이 포함된 릴리스는 없습니다. 우회 방법: websocket 라우트를 별도로 특별 처리하고, include_router()에 전달한 prefix를 앞에 붙여 전체 경로를 직접 재구성하세요.
from fastapi.routing import APIWebSocketRoute, iter_route_contexts
PREFIX = "/api/v1" # app.include_router(router, prefix=PREFIX)에서 사용한 prefix
for ctx in iter_route_contexts(app.routes):
if isinstance(ctx.route, APIWebSocketRoute) and not ctx.path:
full_path = PREFIX + ctx.route.path # 예: /api/v1/stream/{job_id}
else:
full_path = ctx.path
prefix를 정적으로 알 수 없는 경우에는 private _IncludedRouter.include_context.prefix에 저장되어 있지만, 이 API는 내부용이므로 변경될 수 있습니다. 따라서 수정이 반영되기 전까지는 include_router() prefix를 직접 추적하는 것이 더 안전한 방법입니다.