Setting
pip install "uvicorn[standard]"
frontend

- 나는 Vue.js를 좋아해서 Vue로 진행한다.
<template>
<h1> {{ message }}</h1>
</template>
<script>
import axios from 'axios'
export default {
name: 'App',
data() {
return {
message: "undefined",
}
},
created() {
axios.get('http://localhost:8000/hello')
.then((res) => {
this.message = res.data.message;
})
.catch((err) => {
console.log("Error", err);
})
}
}
</script>
<style>
</style>
npm run serve -- --port 5000
backend
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost:5000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credential=True,
allow_methods=['*'],
allow_headers=['*'],
)
@app.get("/hello")
def hello():
return {"message": "Hello, Man ~"}
- main.py에서 hello post 요청을 위한 간단한 로직을 구현한다.
- CORS
- FastAPI에서 FrontServer URL을 CORS 예외 상황으로 두어야 서로 통신이 가능하다.
uvicorn main:app --reload

Router
- Question, Answer, User와 같이 각각의 Domain에 관련된 것들은 해당 domain folder에 두는 것이 깔끔하다.
from fastapi import APIRouter
from database import SessionLocal
from models import Question
router = APIRouter(prefix="/api/question")
@router.get("/list")
def question_list():
db = SessionLocal()
_question_list = db.query(Question).order_by(Question.create_date.desc()).all()
db.close()
return _question_list
- domain/question/question_router.py
routing
: FastAPI가 요청 받은 URL을 해석해 그에 맞는 함수를 실행하여 그 결과를 Return하는 행위
- routing을 위해서는 FastAPI app에 등록하여야 동작한다.
APIRouter
객체의 인자로 prefix는 요청 URL에 반드시 포함되어야하는 값이다.
- 즉,
/api/question/list
라는 요청이 들어오면 prefix를 통해 등록된 router(.py)로 들어가 해당 API가 실행된다는 것이다.
db.close()
는 커넥션 풀을 반환한 것으로 Session을 종료하는 것을 의미하지는 않는다.
- 반환하는 값이 모델 객체들을 담은 list여도 실제로 return 시, json 문자열로 자동 변환된다.
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from domain.question import question_router
app = FastAPI()
origins = [
"http://localhost:5000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(question_router.router)
- main.py를 수정한 것이다. 해당 파일에 app 객체가 있으므로 여기서 진행해주는 것이다.
include_router
함수를 통해 question_router를 등록한 것이다.

- localhost:8000/docs 에서 Test하여 확인