0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vu3×FastAPIのプロジェクト作成方法

Last updated at Posted at 2025-11-17

以下では、Frontend(Vue 3 + TypeScript) Backend(FastAPI) をそれぞれ 別フォルダ に構成するプロジェクトの作成手順を、できるだけシンプルにまとめて説明します。

最終的なディレクトリ構成はこんな形になります:

project-root/
  ├── frontend/   ← Vue3 + TypeScript
  └── backend/    ← FastAPI

Vue3のプロジェクト作成

1. frontend フォルダを作成して Vue3 + TS プロジェクト作成

npm create vue@latest

image.png

2.作成後、依存関係をインストール:

npm install

3.開発サーバー起動

npm run dev

以上が、Frontend(Vue3)のプロジェクト作成完了です。

つづいて、Backend(FastAPI)のプロジェクト作成です。

FastAPIのプロジェクト作成

ルートへ戻ってから:

cd ..
mkdir backend
cd backend

1.仮想環境を作成

python -m venv venv

image.png

下記のコマンドを実行します。

venv\Scripts\activate

2.FastAPI と Uvicorn をインストール

pip install fastapi uvicorn

image.png

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 が自動で再描画します。

image.png

サイト

簡単な例で始めるVue3でTypeScript入門

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?