正在学习
汇总表:环境设置检查清单
7.2 设置 API 项目(Express 或 FastAPI)
在 Claude 能够帮助你设计和实现端点之前,你需要一个干净、可运行的项目骨架。本节为你提供两个同样有效的起点:Express(Node.js)或 FastAPI(Python)。每个启动模板都包含健康检查和一个最小化的内存型任务 API,这样你就可以确认运行时、测试 Claude 的建议,并逐步扩展服务。选择一个技术栈,几分钟内让它跑起来;这里的所有代码都是完整且自包含的。
概念拓展
根据团队熟悉度和生态系统需求来选择你的技术栈。Express 在 Node.js 生态中提供了一个极小的接口面积和最大的灵活性。FastAPI 通过 Pydantic 提供了一流的数据验证和自动生成的 OpenAPI 文档,使模式驱动的开发变得自然而然。无论你选择哪一个,都要保持第一次提交的代码精简:单个进程、内存存储以及简洁的路由布局。这种简洁性使 Claude 能够轻松地推理行为、生成测试并自信地进行重构。
动手示例 A:Express(Node.js)
创建一个新文件夹,然后添加以下两个文件。该启动模板仅使用核心 Express 和内置的 JSON 请求体解析器。它提供了 /health 接口以及 /tasks 的 CRUD 操作,并带有最小化的验证。
package.json
{
"name": "taskflow-express",
"version": "1.0.0",
"description": "TaskFlow API 启动模板(Express)",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "node -e \"console.log('稍后添加测试')\""
},
"dependencies": {
"express": "^4.19.2"
}
}
index.js
import express from "express";
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// 内存存储
let nextId = 1;
const tasks = new Map(); // id -> { id, title, description, completed }
// 健康检查
app.get("/health", (_req, res) => {
res.json({ status: "ok", service: "taskflow-express" });
});
// 创建任务
app.post("/tasks", (req, res) => {
const { title, description = "", completed = false } = req.body || {};
if (typeof title !== "string" || !title.trim()) {
return res.status(400).json({ error: "title is required" });
}
const task = { id: nextId++, title: title.trim(), description, completed: !!completed };
tasks.set(task.id, task);
res.status(201).json(task);
});
// 列出任务
app.get("/tasks", (_req, res) => {
res.json({ items: Array.from(tasks.values()) });
});
// 根据 id 获取任务
app.get("/tasks/:id", (req, res) => {
const id = Number(req.params.id);
const task = tasks.get(id);
if (!task) return res.status(404).json({ error: "not found" });
res.json(task);
});
// 更新任务(完整更新)
app.put("/tasks/:id", (req, res) => {
const id = Number(req.params.id);
if (!tasks.has(id)) return res.status(404).json({ error: "not found" });
const { title, description = "", completed = false } = req.body || {};
if (typeof title !== "string" || !title.trim()) {
return res.status(400).json({ error: "title is required" });
}
const updated = { id, title: title.trim(), description, completed: !!completed };
tasks.set(id, updated);
res.json(updated);
});
// 修补任务(部分更新)
app.patch("/tasks/:id", (req, res) => {
const id = Number(req.params.id);
const current = tasks.get(id);
if (!current) return res.status(404).json({ error: "not found" });
const { title, description, completed } = req.body || {};
if (title !== undefined && (!title || typeof title !== "string")) {
return res.status(400).json({ error: "title must be a non-empty string when provided" });
}
const updated = {
...current,
...(title !== undefined ? { title: title.trim() } : {}),
...(description !== undefined ? { description } : {}),
...(completed !== undefined ? { completed: !!completed } : {})
};
tasks.set(id, updated);
res.json(updated);
});
// 删除任务
app.delete("/tasks/:id", (req, res) => {
const id = Number(req.params.id);
if (!tasks.has(id)) return res.status(404).json({ error: "not found" });
tasks.delete(id);
res.status(204).send();
});
app.listen(PORT, () => {
console.log(`TaskFlow(Express)运行于 http://localhost:${PORT}`);
});
运行它
npm install
npm run start
访问 http://localhost:3000/health。创建一个任务:
curl -s -X POST http://localhost:3000/tasks \
-H "Content-Type: application/json" \
-d '{"title":"第一个任务","description":"试试 Claude 的提示"}'
动手示例 B:FastAPI(Python)
创建一个新文件夹并添加以下两个文件。该启动模板使用 FastAPI 配合 Pydantic 模型,包含 /health 和 /tasks 的 CRUD 操作。它是完全类型化的,并返回一致的 JSON 响应。
requirements.txt
fastapi==0.114.0
uvicorn==0.30.5
app.py
from typing import List, Optional, Dict
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="TaskFlow FastAPI", version="1.0.0")
class TaskCreate(BaseModel):
title: str = Field(min_length=1)
description: Optional[str] = ""
completed: bool = False
class Task(TaskCreate):
id: int
练习题
在为API项目选择技术栈时,哪个因素在文中未被提及为重要?
根据文本,API 项目中第一次提交(first commit)的推荐方法是什么?
Express API starter 为 /tasks 端点支持哪些 HTTP 方法?
Express API 启动器使用内存存储来保存任务。
FastAPI API 入门项目需要 uvicorn 作为依赖项。
在 Express API starter 中,___ 变量用于为任务生成唯一 ID。
FastAPI API 入门项目使用 ___ 类来定义可通过 API 创建的任务的结构。
在 Express API 入门项目中,健康检查端点 (/health) 的用途是什么?
Express API 入门项目在创建新任务时如何处理任务标题的验证?
哪个命令用于在开发模式下启动 Express API starter 并实现自动重启?
根据文本,使用 Claude 进行 API 开发的主要优势是什么?(选择所有适用的)
在设置 Express API 项目时,根据知识点,以下哪项不是初次提交(initial commit)的推荐做法?
以下哪些是设置 FastAPI API 入门项目所需的依赖项?
在一个 Express API 启动项目中,'health' 端点返回一个 JSON 响应,其中 'status' 字段设置为 'ok','service' 字段设置为 'taskflow - express'。
在 FastAPI API 入门模板中,'TaskCreate' 模型有一个 'title' 字段,其最小长度为 ___。
在 API 项目设置中保持首次提交较小的目的是什么?
登录后解锁笔记、知识点解析、AI 问答
立即登录