FastAPI
FastAPI๋?
- ํ์ด์ฌ ๊ธฐ๋ฐ ์คํ์์ค ์น ํ๋ ์์ํฌ
- "FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints."
FastAPI ํน์ง
- ๋น ๋ฆ: (Starlette๊ณผ Pydantic ๋๋ถ์) NodeJS ๋ฐ Go์ ๋๋ฑํ ์ ๋๋ก ๋งค์ฐ ๋์ ์ฑ๋ฅ. ์ฌ์ฉ ๊ฐ๋ฅํ ๊ฐ์ฅ ๋น ๋ฅธ ํ์ด์ฌ ํ๋ ์์ํฌ ์ค ํ๋.
- ๋น ๋ฅธ ์ฝ๋ ์์ฑ: ์ฝ 200%์์ 300%๊น์ง ๊ธฐ๋ฅ ๊ฐ๋ฐ ์๋ ์ฆ๊ฐ. *
- ์ ์ ๋ฒ๊ทธ: ์ฌ๋(๊ฐ๋ฐ์)์ ์ํ ์๋ฌ ์ฝ 40% ๊ฐ์. *
- ์ง๊ด์ : ํ๋ฅญํ ํธ์ง๊ธฐ ์ง์. ๋ชจ๋ ๊ณณ์์ ์๋์์ฑ. ์ ์ ๋๋ฒ๊น ์๊ฐ.
- ์ฌ์: ์ฝ๊ฒ ์ฌ์ฉํ๊ณ ๋ฐฐ์ฐ๋๋ก ์ค๊ณ. ์ ์ ๋ฌธ์ ์ฝ๊ธฐ ์๊ฐ.
- ์งง์: ์ฝ๋ ์ค๋ณต ์ต์ํ. ๊ฐ ๋งค๊ฐ๋ณ์ ์ ์ธ์ ์ฌ๋ฌ ๊ธฐ๋ฅ. ์ ์ ๋ฒ๊ทธ.
- ๊ฒฌ๊ณ ํจ: ์ค๋น๋ ํ๋ก๋์ ์ฉ ์ฝ๋๋ฅผ ์ป์ผ์ญ์์ค. ์๋ ๋ํํ ๋ฌธ์์ ํจ๊ป.
- ํ์ค ๊ธฐ๋ฐ: API์ ๋ํ (์์ ํ ํธํ๋๋) ๊ฐ๋ฐฉํ ํ์ค ๊ธฐ๋ฐ: OpenAPI(์ด์ ์ Swagger๋ก ์๋ ค์ก๋) ๋ฐ JSON ์คํค๋ง
์ค์น
pip install fastapi
pip install "uvicorn[standard]"
- ์ค์๊ฐ ๋ฏธ๋ฆฌ๋ณด๊ธฐ, ํ๋ก๋์ ์ ํ๊ณ ์ถ์ผ๋ฉด uvicorn(ASGI ์๋ฒ)๋ ์ค์นํด์ค๋ค.
from fastapi import FastAPI
app = FastAPI()
#๋ฉ์ธํ์ด์ง๋ก ์ ์์ 'hello'๋ณด๋ด๊ธฐ
@app.get("/")
def comment():
return 'hello'
๊ฐ๋จํ๊ฒ ์ ์ ๊ฐ ๋ฉ์ธํ์ด์ง ์ ์์ hello๋ฅผ ํ์ํ๋๋ก ๊ธฐ๋ฅ์ ์ถ๊ฐํ์๋ค.
uvicorn์ ์คํํด์ ๊ฒฐ๊ณผ๋ฌผ์ ํ์ธํ ์ ์๋ค.
uvicorn main:app --reload
์์ ๊ฐ์ ๊ฒฐ๊ณผ๊ฐ ๋์ค๊ฒ ๋๋๋ฐ ๋งํฌ๋ ์ฃผ์๋ก ๋ค์ด๊ฐ๋ฉด hello๊ฐ ์ถ๋ ฅ๋๋ ๊ฒฐ๊ณผ๋ฌผ์ ํ์ธํ ์ ์๋ค.
๊ฐ๋จํ๊ฒ ๊ธฐ๋ฅ์ ํ๋ ๋ ์ถ๊ฐํด๋ณด๋ฉด
from fastapi import FastAPI
app = FastAPI()
#๋ฉ์ธํ์ด์ง๋ก ์ ์์ 'hello'๋ณด๋ด๊ธฐ
@app.get("/")
def comment():
return 'hello'
#์ถ๊ฐ ๊ธฐ๋ฅ : ๊ฒฝ๋ก๋ฅผ ์ค์ ํ ํ ๋ณด๋ด์ค ๋ฐ์ดํฐ๋ฅผ ์์๋ก ์ค์ ํด๋ณด์๋ค.
@app.get("/test")
def comment():
return {'hi' : 1234}
์์ ํ์๋ ์ฃผ์ ๋งํฌ์ /test๋ฅผ ์ถ๊ฐํ๋ฉด(http://127.0.0.1:8000/test) ์ ๋๋ก ๋๋์ง ํ์ธ์ด ๊ฐ๋ฅํ๋ค.
์ถ๊ฐ์ ์ผ๋ก http://127.0.0.1:8000/docs๋ฅผ ์คํ์ํค๋ฉด ๋ณธ์ธ์ด ๋ง๋ ๊ธฐ๋ฅ์ด ์ด๋ค ๊ฒ๋ค์ด ์๋์ง ๋ฌธ์ํ ํ์ฌ ๋ณด์ฌ์ค๋ค.
๋ค์์ผ๋ก ๋ฉ์ธํ์ด์ง ์ ์์ html ํ์ผ ์ ์ก๊ณผ ๊ฐ์ ๊ธฐ๋ฅ์ ํ๊ณ ์ถ๋ค๋ฉด
from fastapi.responses import FileResponse
์ ์ฝ๋๋ฅผ ์ถ๊ฐํ๋ฉด ๊ฐ๋ฅํ๋ค.
htmlํ์ผ์ ์์ฑํด๋ณด์
<div> ์๋
</div>
from fastapi import FastAPI
app = FastAPI()
from fastapi.responses import FileResponse
#๋ฉ์ธํ์ด์ง ์ ์์ htmlํ์ผ ์ ์ก
@app.get("/")
def comment():
return FileResponse('intex.html')
๋ฉ์ธํ์ด์ง์ htmlํ์ผ์ด ์ ์ก๋๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
class Book(BaseModel):
name: str
content: Optional[str] = None
price: int
app = FastAPI()
@app.post("/books/")
async def create_book(book: Book):
return book
์์๊ฐ์ด app.post()๋ฅผ ์ด์ฉํด ์ ์ ์๊ฒ ๋ฐ์ดํฐ๋ฅผ ๋ฐ์ ์ ์๋ค.
์ฝ๋๋ BaseModel์ ์์ํ Book์ด๋ผ๋ ์๋ก์ด ๋ชจ๋ธ์ ์์ฑํ ๊ฒ์ด๋ค.
{
"name": "james",
"content": "An optional description",
"price": 100
}
์ JSON ๊ฐ์ฒด๋ฅผ ์ ๋ ฅ๋ฐ๊ณ request body๋ก ์ค์ ํ์ฌ API๋ฅผ ํธ์ถํ๋ค
๋ฐฑ์๋๋ ์ฒ์์ด๋ผ ์์ง ์ดํด๊ฐ ์๋ฒฝํ ๋์ง ์๋๋ค