메타데이터와 문서 URL
메타데이터와 문서 URL (Metadata and Docs URLs)
FastAPI 애플리케이션에서 여러 가지 메타데이터 설정을 커스터마이즈할 수 있습니다.
출처: 공식문서
API 메타데이터 (Metadata for API)
OpenAPI 스펙과 자동 API 문서 UI에 사용되는 다음 필드들을 설정할 수 있습니다:
| 파라미터 | 타입 | 설명 |
|---|---|---|
title |
str |
API의 제목입니다. |
summary |
str |
API에 대한 짧은 요약입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능합니다. |
description |
str |
API에 대한 짧은 설명입니다. Markdown을 쓸 수 있습니다. |
version |
str |
API의 버전입니다. 이는 OpenAPI의 버전이 아니라 여러분 자신의 애플리케이션 버전입니다. 예: 2.5.0 |
terms_of_service |
str |
API의 서비스 약관 URL입니다. 제공한다면 반드시 URL이어야 합니다. |
contact |
dict |
노출된 API의 연락처 정보입니다. 여러 필드를 담을 수 있습니다. |
contact 필드
| 파라미터 | 타입 | 설명 |
|---|---|---|
name |
str |
연락 담당자/조직의 식별 이름입니다. |
url |
str |
연락처 정보를 가리키는 URL입니다. 반드시 URL 형식이어야 합니다. |
email |
str |
연락 담당자/조직의 이메일 주소입니다. 반드시 이메일 주소 형식이어야 합니다. |
license_info 필드
| 파라미터 | 타입 | 설명 |
|---|---|---|
name |
str |
필수(license_info가 설정된 경우). API에 사용되는 라이선스 이름입니다. |
identifier |
str |
API에 대한 SPDX 라이선스 표현식입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능합니다. |
url |
str |
API에 사용되는 라이선스 URL입니다. 반드시 URL 형식이어야 합니다. |
다음과 같이 설정할 수 있습니다:
from fastapi import FastAPI
description = """
ChimichangApp API helps you do awesome stuff. 🚀
## Items
You can **read items**.
## Users
You will be able to:
* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""
app = FastAPI(
title="ChimichangApp",
description=description,
summary="Deadpool's favorite app. Nuff said.",
version="0.0.1",
terms_of_service="http://example.com/terms/",
contact={
"name": "Deadpoolio the Amazing",
"url": "http://x-force.example.com/contact/",
"email": "[email protected]",
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
)
@app.get("/items/")
async def read_items():
return [{"name": "Katana"}]
!!! tip "팁"
description 필드에 Markdown을 쓸 수 있으며, 출력물에도 그대로 렌더링됩니다.
이 설정을 하면 자동 API 문서가 이런 모습이 됩니다.
라이선스 식별자 (License identifier)
OpenAPI 3.1.0과 FastAPI 0.99.0부터, license_info를 url 대신 identifier로 설정할 수도 있습니다.
예를 들어:
from fastapi import FastAPI
description = """
ChimichangApp API helps you do awesome stuff. 🚀
## Items
You can **read items**.
## Users
You will be able to:
* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""
app = FastAPI(
title="ChimichangApp",
description=description,
summary="Deadpool's favorite app. Nuff said.",
version="0.0.1",
terms_of_service="http://example.com/terms/",
contact={
"name": "Deadpoolio the Amazing",
"url": "http://x-force.example.com/contact/",
"email": "[email protected]",
},
license_info={
"name": "Apache 2.0",
"identifier": "Apache-2.0",
},
)
@app.get("/items/")
async def read_items():
return [{"name": "Katana"}]
태그 메타데이터 (Metadata for tags)
openapi_tags 파라미터로, 경로 동작들을 그룹 짓는 데 사용하는 서로 다른 태그들에 대한 추가 메타데이터를 넣을 수도 있습니다.
각 태그마다 딕셔너리 하나가 들어 있는 리스트를 받습니다.
각 딕셔너리는 다음을 담을 수 있습니다:
name(필수): 경로 동작 과APIRouter의tags파라미터에서 사용하는 것과 같은 태그 이름을 담은str입니다.description: 태그에 대한 짧은 설명을 담은str입니다. Markdown을 쓸 수 있고 문서 UI에 표시됩니다.externalDocs: 외부 문서를 설명하는dict로, 다음을 담습니다:description: 외부 문서에 대한 짧은 설명을 담은str입니다.url(필수): 외부 문서의 URL을 담은str입니다.
태그 메타데이터 만들기 (Create metadata for tags)
users와 items 태그를 쓰는 예제로 시도해 봅시다.
태그에 대한 메타데이터를 만들고 openapi_tags 파라미터에 넘기세요:
from fastapi import FastAPI
tags_metadata = [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
},
{
"name": "items",
"description": "Manage items. So _fancy_ they have their own docs.",
"externalDocs": {
"description": "Items external docs",
"url": "https://fastapi.tiangolo.com/",
},
},
]
app = FastAPI(openapi_tags=tags_metadata)
@app.get("/users/", tags=["users"])
async def get_users():
return [{"name": "Harry"}, {"name": "Ron"}]
@app.get("/items/", tags=["items"])
async def get_items():
return [{"name": "wand"}, {"name": "flying broom"}]
설명 안에 Markdown을 쓸 수 있다는 점을 주목하세요. 예를 들어 "login"은 굵게(login) 표시되고, "fancy"는 기울임꼴(fancy)로 표시됩니다.
!!! tip "팁" 사용하는 모든 태그에 메타데이터를 추가할 필요는 없습니다.
태그 사용하기 (Use your tags)
경로 동작(과 APIRouter)의 tags 파라미터를 사용해 서로 다른 태그에 할당하세요:
from fastapi import FastAPI
tags_metadata = [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
},
{
"name": "items",
"description": "Manage items. So _fancy_ they have their own docs.",
"externalDocs": {
"description": "Items external docs",
"url": "https://fastapi.tiangolo.com/",
},
},
]
app = FastAPI(openapi_tags=tags_metadata)
@app.get("/users/", tags=["users"])
async def get_users():
return [{"name": "Harry"}, {"name": "Ron"}]
@app.get("/items/", tags=["items"])
async def get_items():
return [{"name": "wand"}, {"name": "flying broom"}]
!!! note "참고" 태그에 대한 더 자세한 내용은 Path Operation Configuration을 참고하세요.
문서 확인하기 (Check the docs)
이제 문서를 확인하면 추가 메타데이터가 모두 표시됩니다.
태그 순서 (Order of tags)
각 태그 메타데이터 딕셔너리의 순서가 문서 UI에 표시되는 순서도 결정합니다.
예를 들어 알파벳 순서로는 items 다음에 users가 와야 하지만, 우리가 users 메타데이터를 리스트의 첫 번째 딕셔너리로 넣었기 때문에 users가 먼저 표시됩니다.
OpenAPI URL (OpenAPI URL)
기본적으로 OpenAPI 스키마는 /openapi.json에서 제공됩니다.
하지만 openapi_url 파라미터로 설정할 수 있습니다.
예를 들어 /api/v1/openapi.json에서 제공되도록 설정하려면:
from fastapi import FastAPI
app = FastAPI(openapi_url="/api/v1/openapi.json")
@app.get("/items/")
async def read_items():
return [{"name": "Foo"}]
OpenAPI 스키마를 완전히 비활성화하고 싶다면 openapi_url=None으로 설정할 수 있는데, 그러면 그것을 사용하는 문서 UI도 비활성화됩니다.
문서 URL (Docs URLs)
포함된 두 개의 문서 UI를 설정할 수 있습니다:
- Swagger UI:
/docs에서 제공됩니다.docs_url파라미터로 URL을 설정할 수 있습니다.docs_url=None으로 설정하면 비활성화할 수 있습니다.
- ReDoc:
/redoc에서 제공됩니다.redoc_url파라미터로 URL을 설정할 수 있습니다.redoc_url=None으로 설정하면 비활성화할 수 있습니다.
예를 들어 Swagger UI를 /documentation에서 제공하고 ReDoc을 비활성화하려면:
from fastapi import FastAPI
app = FastAPI(docs_url="/documentation", redoc_url=None)
@app.get("/items/")
async def read_items():
return [{"name": "Foo"}]
더 알아보기 (Learn more)
FastAPI(...)생성자에서title,version,description,contact,license_info등으로 API 메타데이터를 지정할 수 있습니다.openapi_tags로 태그 그룹에 대한 설명과 외부 문서 링크를 달 수 있고, 리스트 순서대로 문서에 표시됩니다.openapi_url,docs_url,redoc_url로 스키마/문서 UI의 URL을 바꾸거나None으로 꺼둘 수 있습니다.