IT기술/파이썬 (python)

FastAPI 프로젝트 설정

후스파 2025. 3. 23. 00:32
반응형
FastAPI 다이어그램

FastAPI와 Svelte를 사용한 웹 애플리케이션 구축에 대해 자세히 설명해 드리겠습니다.

FastAPI 프로젝트 설정

  • PyCharm에서 새 프로젝트를 생성합니다.
  • main.py 파일에 기본 FastAPI 코드를 작성합니다:
 
 
from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def hello():
    return {"message": "first api!"}
  • 터미널에서 uvicorn을 설치합니다:
pip install "uvicorn[standard]"
 
 
  • 웹 서버를 실행합니다:
uvicorn main:app --reload
 
 
  • API 테스트를 위해 브라우저에서 다음 주소를 확인합니다.
    • Swagger UI: http://127.0.0.1:8000/docs
    • ReDoc: http://127.0.0.1:8000/redoc

Svelte 설정

  1. VSCode를 실행하고 src 폴더에 App.svelte 파일을 생성합니다.
  2. App.svelte에 기본 코드를 작성합니다:
 
 
<h1>first api</h1>
  1. Svelte 개발 서버를 실행하고 http://localhost:5173/에서 확인합니다.
  2. app.css 파일의 내용을 모두 삭제합니다.

FastAPI와 Svelte 연동

  • App.svelte에 FastAPI 연동 코드를 추가합니다:
<script>
  let message;

  fetch("http://127.0.0.1:8000/hello").then((response) => {
    response.json().then((json) => {
      message = json.message;
    });
  });
</script>

<h1>{message}</h1>
 
 
  • CORS 문제 해결을 위해 main.py에 미들웨어를 추가합니다:
from starlette.middleware.cors import CORSMiddleware

origins = [
    "http://127.0.0.1:5173",
    "http://localhost:5173",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
 
 
  • 개선된 Svelte Fetch 사용 코드:
<script>
  async function hello() {
    const res = await fetch("http://127.0.0.1:8000/hello");
    const json = await res.json();

    if (res.ok) {
      return json.message;
    } else {
      alert("error");
    }
  }

  let promise = hello();
</script>

{#await promise}
  <p>...waiting</p>
{:then message}
  <h1>{message}</h1>
{/await}
 
 
 

이 코드는 비동기 작업의 상태를 관리하며, API 호출 결과를 효과적으로 표시합니다.

FastAPI와 Svelte를 조합하면 강력하고 효율적인 웹 애플리케이션을 구축할 수 있습니다. FastAPI는 고성능 백엔드 API를 제공하고, Svelte는 반응적이고 가벼운 프런트엔드 인터페이스를 제공합니다.

 

 

[FastAPI] FastAPI 프로젝트 맛보기

PyCharm에서 FastAPI 설정 PyCharm 실행 PyCharm을 실행합니다. 새 프로젝트를 생성하거나 기존 ...

blog.naver.com

 

 

[FastAPI + Svelte 완벽 가이드] 풀스택 웹 개발 환경 구축하기

FastAPI와 Svelte를 결합한 풀스택 웹 애플리케이션 개발 환경 구축 방법을 상세히 알아보겠습니다. 이 가이드는 IDE 설치부터 FastAPI와 Svelte 설정까지 모든 단계를 포함합니다. 1. IDE 설치 및 설정Fast

hoosfa.tistory.com

 

반응형