以下では、Frontend(Vue 3 + TypeScript) と Backend(FastAPI) をそれぞれ 別フォルダ に構成するプロジェクトの作成手順を、できるだけシンプルにまとめて説明します。
最終的なディレクトリ構成はこんな形になります:
project-root/
├── frontend/ ← Vue3 + TypeScript
└── backend/ ← FastAPI
Vue3のプロジェクト作成
1. frontend フォルダを作成して Vue3 + TS プロジェクト作成
npm create vue@latest
2.作成後、依存関係をインストール:
npm install
3.開発サーバー起動
npm run dev
以上が、Frontend(Vue3)のプロジェクト作成完了です。
つづいて、Backend(FastAPI)のプロジェクト作成です。
FastAPIのプロジェクト作成
ルートへ戻ってから:
cd ..
mkdir backend
cd backend
1.仮想環境を作成
python -m venv venv
下記のコマンドを実行します。
venv\Scripts\activate
2.FastAPI と Uvicorn をインストール
pip install fastapi uvicorn
3.サーバー起動
uvicorn main:app --reload
FastAPI に CORS 設定を追加
backend/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# ---- CORS 設定 ----
origins = [
"http://localhost:5173", # Vueの開発サーバー
"http://127.0.0.1:5173", # 念のため追加
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------
@app.get("/")
def read_root():
return {"message": "Hello from FastAPI!"}
以上がBackendのプロジェクトの作成でした。
Vueに表示してみる
App.vue
<script setup>
import { ref, onMounted } from 'vue'
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
// 表示用のリアクティブ変数
const message = ref('読み込み中...')
// API を呼び出す
onMounted(async () => {
try {
const res = await fetch("http://localhost:8000/")
const data = await res.json()
message.value = data.message
} catch (error) {
message.value = "サーバーに接続できませんでした"
console.error(error)
}
})
</script>
<template>
<header>
<img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />
<div class="wrapper">
<HelloWorld msg="You did it!" />
</div>
</header>
<!-- ここに FastAPI からのデータを表示 -->
<h1>{{ message }}</h1>
<main>
<TheWelcome />
</main>
</template>
🔍 ポイント解説
■✔ ref() を使う
React のuseState()のように、Vue のデータはrefに入れないとテンプレートで使えません。
■✔ onMounted() で API を呼ぶ
Vue コンポーネントが mount されたら API を呼ぶのが一般的です。
■✔ message.value を更新
ref の値を変えると Vue が自動で再描画します。
サイト
簡単な例で始めるVue3でTypeScript入門



