文、意如
Python環境
安裝fastapi、uvicorn
一、開啟終端機
安裝指令:pip install fastapi

安裝指令:pip install uvicorn

python程式碼:
mytest.py
# 匯入 FastAPI 主框架
from fastapi import FastAPI
# 匯入處理 CORS(跨來源資源分享)的中介軟體
from fastapi.middleware.cors import CORSMiddleware
# 建立 FastAPI 應用程式實例
app = FastAPI()
# 設定允許的跨域來源(這裡設為 "*" 代表所有來源都允許)
origins = [
"*"
]
# 加入 CORS 中介軟體,讓前端可以跨域請求此 API
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # 允許的來源清單(可改為 ['http://localhost:3000'] 等)
allow_credentials=True, # 是否允許傳送 Cookie 或認證資訊
allow_methods=["*"], # 允許的 HTTP 方法(如 GET、POST、PUT、DELETE)
allow_headers=["*"], # 允許的請求標頭(如 Content-Type、Authorization)
)
# 定義一個 GET 路由 "/api/data"
@app.get("/api/data")
async def get_data():
# 回傳一筆包含陣列與物件的 JSON 資料
return {
"status": "success",
"user": {
"id": 1,
"name": "小明",
"email": "xiaoming@example.com"
},
"tags": ["python", "fastapi", "ajax"],
"articles": [
{"id": 101, "title": "FastAPI 入門教學", "likes": 120},
{"id": 102, "title": "如何用 AJAX 呼叫 API", "likes": 95},
{"id": 103, "title": "前後端 CORS 跨域完整解析", "likes": 80}
],
"meta": {
"api_version": "1.0.0",
"timestamp": "2025-05-29T10:00:00Z"
}
}
回傳資料結構說明:
{
"status": "success",
"user": { ... }, # 一個物件,代表使用者資料
"tags": [ ... ], # 一個字串陣列,代表標籤
"articles": [ ... ], # 一個陣列,每個元素是文章的物件
"meta": { ... } # 其他額外資訊,例如 API 版本與時間戳
}
啟動伺服器

使用postman測試回傳資料(非必須)

使用html+ajax
<html>
<head>
<meta>
<title>Fetch FastAPI 資料</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h2>API 資料顯示:</h2>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://localhost:8000/api/data',
success: function (info) {
console.log(info);
},
error: function (data) {
console.log("請求失敗");
}
});
});
</script>
</body>
</html>

資料呈現於網頁表格
<html>
<head>
<meta>
<title>Fetch FastAPI 資料</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
table {
border-collapse: collapse;
margin-bottom: 20px;
}
th, td {
border: 1px solid #999;
padding: 8px 12px;
}
th {
background-color: #eee;
}
</style>
</head>
<body>
<h2>使用者資訊</h2>
<table id="userTable"></table>
<h2>標籤 Tags</h2>
<ul id="tagsList"></ul>
<h2>文章列表</h2>
<table id="articlesTable"></table>
<h2>Meta 資訊</h2>
<table id="metaTable"></table>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://localhost:8000/api/data',
success: function (info) {
// 使用者資料
const user = info.user;
$('#userTable').html(`
<tr><th>ID</th><td>${user.id}</td></tr>
<tr><th>姓名</th><td>${user.name}</td></tr>
<tr><th>Email</th><td>${user.email}</td></tr>
`);
// 標籤資料
const tags = info.tags;
tags.forEach(tag => {
$('#tagsList').append(`<li>${tag}</li>`);
});
// 文章資料
const articles = info.articles;
let articleHtml = `
<tr><th>ID</th><th>標題</th><th>按讚數</th></tr>
`;
articles.forEach(article => {
articleHtml += `
<tr>
<td>${article.id}</td>
<td>${article.title}</td>
<td>${article.likes}</td>
</tr>
`;
});
$('#articlesTable').html(articleHtml);
// Meta 資訊
const meta = info.meta;
$('#metaTable').html(`
<tr><th>API 版本</th><td>${meta.api_version}</td></tr>
<tr><th>時間戳</th><td>${meta.timestamp}</td></tr>
`);
},
error: function () {
alert("請求失敗,請確認後端有開啟 & CORS 設定正確");
}
});
});
</script>
</body>
</html>

Yiru@Studio - 關於我 - 意如