🪴 Daily gardening

Search

Search IconIcon to open search

readme.io 세팅

Last updated Dec 2, 2022

# API References Try it Authentication 추가하기

# FastAPI에서 추가하기

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from fastapi import FastAPI, Security
from fastapi.security import APIKeyHeader

x_api_key = APIKeyHeader(name="x-api-key", auto_error=False)

async def auth(x_api_key: str = Security(x_api_key)):
  if x_api_key == get_config("API_KEY"):
    return x_api_key
  else:
    raise UnauthorizedException()

router = APIRouter(dependencies= [Depends(auth)])

app = FastAPI()
app.include_router(router)

swagger에서도 Authorize가 생긴 것을 볼 수 있다. openapi.json 확인하면 components.securitySchemes 가 추가 되어있다.

1
2
3
4
5
6
7
8
securityDefinitions: {
    API_KEY: {
       type: "apiKey",
       name: "x-api-key",
       in: "header",
       "x-default": "demo-api-key",
   },
},