正在学习
Summary Table: Environment Setup Checklist
7.2 Setting Up the API Project (Express or FastAPI)
Before Claude can help you design and implement endpoints, you need a clean, runnable project skeleton. This section gives you two equally valid starting points: Express (Node.js) or FastAPI (Python). Each starter includes a health check and a minimal in-memory tasks API so you can confirm the runtime, exercise Claude’s suggestions, and grow the service incrementally. Pick one stack and get it running in a few minutes; all code here is complete and self-contained.
Concept Development
Choose your stack based on team familiarity and ecosystem needs. Express offers a tiny surface area with maximal flexibility in the Node.js ecosystem. FastAPI provides first-class data validation via Pydantic and automatic OpenAPI docs, making schema-driven development natural. Whichever you choose, keep the first commit small: a single process, in-memory storage, and a straightforward route layout. That simplicity makes it easy for Claude to reason about behavior, generate tests, and refactor confidently.
Hands-On Example A: Express (Node.js)
Create a new folder, then add these two files. This starter uses only core Express and the built-in JSON body parser. It provides/health plus/tasks CRUD with minimal validation.
package.json
{
"name": "taskflow-express",
"version": "1.0.0",
"description": "TaskFlow API starter (Express)",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "node -e \"console.log('Add tests later')\""
},
"dependencies": {
"express": "^4.19.2"
}
}
index.js
import express from "express";
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// In-memory store
let nextId = 1;
const tasks = new Map(); // id -> { id, title, description, completed }
// Health check
app.get("/health", (_req, res) => {
res.json({ status: "ok", service: "taskflow-express" });
});
// Create task
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);
});
// List tasks
app.get("/tasks", (_req, res) => {
res.json({ items: Array.from(tasks.values()) });
});
// Get task by 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);
});
// Update task (full update)
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);
});
// Patch task (partial update)
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);
});
// Delete task
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) running on http://localhost:${PORT}`);
});
Run it
npm install
npm run start
Visit http://localhost:3000/health. Create a task:
```bash
curl -s -X POST http://localhost:3000/tasks \
-H "Content-Type: application/json" \
-d '{"title":"First task","description":"Try Claude prompts"}'
Hands-On Example B: FastAPI (Python)
Create a new folder and add the following two files. This starter uses FastAPI with Pydantic models and includes/health plus/tasks CRUD. It is fully typed and returns consistent JSON responses.
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
练习题
When choosing a stack for an API project, which factor is NOT mentioned as important in the text?
What is the recommended approach for the first commit in an API project according to the text?
What HTTP methods are supported by the Express API starter for the /tasks endpoint?
The Express API starter uses in-memory storage for tasks.
The FastAPI API starter requires uvicorn as a dependency.
In the Express API starter, the ___ variable is used to generate unique IDs for tasks.
The FastAPI API starter uses the ___ class to define the structure of a task that can be created via the API.
What is the purpose of the health check endpoint (/health) in the Express API starter?
How does the Express API starter handle validation for the task title when creating a new task?
Which command is used to start the Express API starter in development mode with automatic restarts?
What are the key benefits of using Claude in API development according to the text? (Select all that apply)
When setting up an Express API project, which of the following is NOT a recommended practice for the initial commit according to the knowledge points?
Which of the following are required dependencies for setting up a FastAPI API starter project?
In an Express API starter project, the 'health' endpoint returns a JSON response with a 'status' field set to 'ok' and a'service' field set to 'taskflow - express'.
In the FastAPI API starter, the 'TaskCreate' model has a 'title' field with a minimum length of ___.
What is the purpose of keeping the first commit small in an API project setup?
登录后解锁笔记、知识点解析、AI 问答
立即登录