Vue + FastAPI 段階学習
テクノロジ系 / L14 vue-fastapi-3steps — Vue + FastAPI 段階学習 (Vue 単体 → FastAPI 単体 → 連携)
Vue + FastAPI 段階学習
3つのステップで「フロント・バック・連携」を体験する
- step1: Vue 単体(バックエンドなし)
- step2: FastAPI 単体(フロントエンドなし)
- step3: Vue + FastAPI 連携
> このスライドでは PowerShell 表記でコマンドを示す。 Mac / Linux 用の bash 表記は各 step フォルダの README.md に併記してある。
step1: Vue 単体
目的
ボタンを押すと文字が変わる → リアクティブを体感
起動
cd step1-vue npm install npm run dev
ブラウザで http://localhost:5173 を開く
step1: App.vue
<script setup>
import { ref } from 'vue'
const message = ref('Hello from Vue')
function greet() {
message.value = 'ボタンを押したよ'
}
</script>
<template>
<p>{{ message }}</p>
<button @click="greet">押す</button>
</template>step2: FastAPI 単体
目的
ブラウザで URL を叩くと JSON が返る → API を体感
起動
cd step2-fastapi python -m venv .venv .\.venv\Scripts\Activate.ps1 pip install -r requirements.txt python -m uvicorn main:app --reload
ブラウザで http://localhost:8000/hello を開く
step2: main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def hello():
return {"message": "Hello from FastAPI"}step3: Vue + FastAPI 連携
目的
Vue(フロント)から FastAPI(バック)を呼ぶ
ターミナル2つ必要
| ターミナル | 役割 | ポート |
|---|---|---|
| 1 | FastAPI(Python) | 8000 |
| 2 | Vue(Node.js) | 5173 |
別プロセスなので両方起動し続ける
step3: 起動手順
ターミナル1(バックエンド)
cd step3-connect .\.venv\Scripts\Activate.ps1 python -m uvicorn main:app --reload
ターミナル2(フロントエンド)
cd step3-connect\frontend npm install npm run dev
ブラウザで http://localhost:5173 を開く
step1 → step3: App.vue の差分
greet() 関数の中身だけ が変わる
function greet() {
- message.value = 'ボタンを押したよ'
+ fetch('http://localhost:8000/hello')
+ .then(r => r.json())
+ .then(d => message.value = d.message)
}直接代入 → FastAPI から取得して代入
step2 → step3: main.py の差分
CORS ミドルウェアの2行追加 だけ
from fastapi import FastAPI
+ from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
+ app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
+ )
@app.get("/hello")
def hello():
return {"message": "Hello from FastAPI"}/hello の中身は step2 と完全に同じ
なぜ CORS が必要か
ブラウザの オリジン違いを拒否する 仕組み
Vue : http://localhost:5173 ← オリジンA FastAPI: http://localhost:8000 ← オリジンB
ポートが違うと 別オリジン 扱い → 標準でブロック
FastAPI 側が「許可するよ」と返さないと fetch が失敗する
共通ファイルの整理
step1 と step3 で App.vue 以外は同一
| ファイル | step1 | step3 |
|---|---|---|
| package.json | ✅ 同じ | ✅ 同じ |
| vite.config.js | ✅ 同じ | ✅ 同じ |
| index.html | ✅ 同じ | ✅ 同じ |
| src/main.js | ✅ 同じ | ✅ 同じ |
| src/style.css | ✅ 同じ | ✅ 同じ |
| src/App.vue | ❌ 違う | ❌ 違う |
→ 学ぶべきは App.vue だけ
まとめ
| step | 何を学ぶ | 触るファイル |
|---|---|---|
| 1 | Vue のリアクティブ | App.vue |
| 2 | API の概念 | main.py |
| 3 | フロント↔バック連携 | App.vue に fetch / main.py に CORS |
step3 は step1 と step2 を 数行ずつ足すだけ で完成する