์ค๋์ FastAPI๋ฅผ ์ฌ์ฉํด์ API๋ฅผ ์ ๊ณตํ ๋ API ํค๋ฅผ ์ ์ฉํ๋ ๋ฐฉ๋ฒ์ ๋ํด ์์๋ณด๋ ค๊ณ ํด์. API ํค๊ฐ ๋ฌด์์ธ์ง, ์ ์ฌ์ฉํ๋์ง, ๊ทธ๋ฆฌ๊ณ ์ด๋ป๊ฒ ์ ์ฉํ๋์ง ์ค๋ช ํด ๋ณผ๊ฒ์ ~!
API ํค๋ ๋ฌด์์ธ๊ฐ์?
API ํค(API Key)๋ ์ ํ๋ฆฌ์ผ์ด์ ์ด API๋ฅผ ํธ์ถํ ๋ ์ธ์ฆ ๋ฐ ๊ถํ ๋ถ์ฌ๋ฅผ ์ํด ์ฌ์ฉํ๋ ๊ณ ์ ์๋ณ์์์. API ํค๋ ๋ค์๊ณผ ๊ฐ์ ์ด์ ๋ก ์ฌ์ฉ๋ผ์:
- ์ธ์ฆ ๋ฐ ๊ถํ ๋ถ์ฌ: ํด๋ผ์ด์ธํธ ์ ํ๋ฆฌ์ผ์ด์ ์ด API์ ์ ๊ทผํ ์ ์๋ ๊ถํ์ด ์๋์ง ํ์ธ
- ์ฌ์ฉ ์ถ์ ๋ฐ ๋ชจ๋ํฐ๋ง: ์ด๋ค ํด๋ผ์ด์ธํธ๊ฐ ์ด๋ค API ํธ์ถ์ ํ๋์ง ์ถ์ ํ๊ณ ๋ชจ๋ํฐ๋ง
- ์์ฒญ ์ ํ: ํน์ ํด๋ผ์ด์ธํธ๊ฐ ์ผ์ ์๊ฐ ๋ด์ ๋ณด๋ผ ์ ์๋ ์์ฒญ ์๋ฅผ ์ ํํ ์ ์์
FastAPI์์ API ํค ์ ์ฉํ๊ธฐ
API ํค๋ฅผ ์ฌ์ฉํ ์ธ์ฆ ๋ฏธ๋ค์จ์ด ์์ฑํ๊ธฐ
from fastapi import FastAPI, Depends, HTTPException, Security
from fastapi.security.api_key import APIKeyHeader
app = FastAPI()
API_KEY = "your-secret-api-key"
API_KEY_NAME = "access_token"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
def get_api_key(api_key_header: str = Security(api_key_header)):
if api_key_header == API_KEY:
return api_key_header
else:
raise HTTPException(
status_code=403, detail="Could not validate credentials"
)
@app.get("/protected-route")
async def protected_route(api_key: str = Depends(get_api_key)):
return {"message": "You have access to this route"}
@app.get("/unprotected-route")
async def unprotected_route():
return {"message": "This route is open to everyone"}
Python์ผ๋ก API ํธ์ถํ๊ธฐ
import requests
url = "http://localhost:8000/protected-route"
headers = {
"access_token": "your-secret-api-key"
}
response = requests.get(url, headers=headers)
print(response.json())
curl๋ก API ํธ์ถํ๊ธฐ
curl -X 'GET' \
'http://localhost:8000/protected-route' \
-H 'access_token: your-secret-api-key'
์ด๋ ๊ฒ ์ค์ ํ๋ฉด ๋ณดํธ๋ ๊ฒฝ๋ก(/protected-route)์ ์ ๊ทผํ ๋ ์ฌ๋ฐ๋ฅธ API ํค๊ฐ ํ์ํด์. API ํค๊ฐ ์ ํจํ์ง ์์ผ๋ฉด 403 ์ค๋ฅ๋ฅผ ๋ฐํํ๊ฒ ๋์ฃ ! ์ฌ๊ธฐ๊น์ง FastAPI์์ API ํค๋ฅผ ์ ์ฉํ๋ ๋ฐฉ๋ฒ์ ์์๋ณด์์ด์. API ๊ฐ๋ฐ ์ ๊ฐ๋จํ๊ฒ ๊ณ ๋ คํด ๋ณด๋๊ฑธ ์ถ์ฒ๋๋ ค์ !