FrameWork/FastAPI
API호출 라이브러리 생성
mansoorrr
2024. 5. 27. 19:55
화면에 데이터를 보여주기 위해서는 백엔드에 데이터를 요청해야 한다. 이는 엄청 많아지는 routes안의 svelte파일들에 fetch("http:127.0.0.1/8000/......)를 매번 써야 한다는 것을 의미한다. 이 귀찮음을 해결하기 위해 라이브러리로 만들어 놓는다.
[frontend/lib/api.js 생성]
const fastapi = (operation, url, params, success_callback, failure_callback) => {
let method = operation; // get, post
let content_type = 'application/json';
let body = JSON.stringify(params); // 요청데이터 상세를 json문자열로 변환
let _url = 'http://127.0.0.1:8000' + url; //fetch할 url 생성
//get방식을 제외한 나머지에 사용될 options
let options = {
method: method,
headers: {
"Content-Type": content_type
}
}
// get방식으로 fetch일 경우
if (method==="get") {
// url을 params에 맞춰서 재정의(URLSearchParams사용)
_url += "?" + new URLSearchParams(params);
}
// get방식이 아닌 경우
if (method !== "get") {
options['body'] = body;
}
fetch(_url, option).then((response) => {
response.json().then((json) => {
if (response.status >=200 && response.status < 300) {
// response응답이 200~299: 프로토콜 성공
if (success_callback) {
// 성공시 함수 있으면 실행
success_callback(json);
}
} else {
// response응답 실패
if (failure_callback) {
// 실패시 함수 입력되면 실행
failure_callback(json);
} else {
// 실패시 함수 입력되지 않으면 alert로 출력
alert(JSON.stringify(json));
}
}
}).catch(error => {
alert(JSON.stringify(error)); // 에러발생시 에러 alert로 출력
})
})
}
[호스트명을 환경 파일에서 불러오기]
- 현재 호스트 서버가 http://127.0.0.1:8000으로 지정되어 있음
- 이 서버는 언제든 변경될 수 있음
- 따라서 환경파일에서 설정하는것을 권장
- frontend/.env생성: svelte에서 환경변수를 읽어오기 위해서는 반드시 변수 명이 VITE로 시작해야 함
// ----------- frontend/.env
VITE_SERVER_URL = http://127.0.0.1:8000
- lib/api.js수정
const fastapi = (operation, url, params, success_callback, failure_callback) => {
let method = operation; // get, post
let content_type = 'application/json';
let body = JSON.stringify(params); // 요청데이터 상세를 json문자열로 변환
let _url = import.meta.env.VITE_SERVER_URL + url; //fetch할 url 생성 -> 요부분 환경변수로 변환
- Home.svelte수정: get_question_list의 fetch부분 수정
function get_question_list() {
fastapi("get", "/api/question/list", {}, (json) => {
question_list = json;
})
}