正在学习
7.1 Overview and Objectives
In-memory storage
_next_id: int = 1 _tasks: Dict[int, Task] = {}
@app.get("/health") def health() -> Dict[str, str]: return {"status": "ok", "service": "taskflow-fastapi"}
@app.post("/tasks", response_model=Task, status_code=201) def create_task(payload: TaskCreate) -> Task: global _next_id task = Task(id=_next_id, **payload.model_dump()) _tasks[task.id] = task _next_id += 1 return task
@app.get("/tasks", response_model=List[Task]) def list_tasks() -> List[Task]: return list(_tasks.values())
@app.get("/tasks/{task_id}", response_model=Task) def get_task(task_id: int) -> Task: task = _tasks.get(task_id) if not task: raise HTTPException(status_code=404, detail="not found") return task
@app.put("/tasks/{task_id}", response_model=Task) def put_task(task_id: int, payload: TaskCreate) -> Task: if task_id not in _tasks: raise HTTPException(status_code=404, detail="not found") updated = Task(id=task_id, **payload.model_dump()) _tasks[task_id] = updated return updated
class TaskPatch(BaseModel): title: Optional[str] = Field(default=None) description: Optional[str] = None completed: Optional[bool] = None
@app.patch("/tasks/{task_id}", response_model=Task) def patch_task(task_id: int, payload: TaskPatch) -> Task: current = _tasks.get(task_id) if not current: raise HTTPException(status_code=404, detail="not found") data = current.model_dump() patch = payload.model_dump(exclude_unset=True) if "title" in patch: if not patch["title"] or not isinstance(patch["title"], str): raise HTTPException(status_code=400, detail="title must be non-empty string") data["title"] = patch["title"] if "description" in patch: data["description"] = patch["description"] if "completed" in patch: data["completed"] = bool(patch["completed"]) updated = Task(**data) _tasks[task_id] = updated return updated
@app.delete("/tasks/{task_id}", status_code=204) def delete_task(task_id: int) -> None: if task_id not in _tasks: raise HTTPException(status_code=404, detail="not found") del _tasks[task_id]
Run it
```bash
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt
uvicorn app:app --reload
Visit http://localhost:8000/health. Create a task:
curl -s -X POST http://localhost:8000/tasks \
-H "Content-Type: application/json" \
-d '{"title":"First task","description":"Try Claude prompts"}'
Browse interactive docs at http://localhost:8000/docs.
Clarification Table: Choose Your Starter
| Criterion | Express (Node.js) | FastAPI (Python) |
|---|---|---|
| Learning curve | Very small, minimal abstractions | Small; strong typing and schema focus |
| Built-in validation | Manual or third-party libs | Pydantic models, automatic |
| Docs generation | External tooling | Automatic OpenAPI and Swagger UI |
| Typical use | JS/TS shops, microservices, lightweight APIs | Python teams, data/ML APIs, schema-first design |
| Startup commands | npm install then npm run start | pip install -r requirements.txt then uvicorn app:app --reload |
You now have a minimal but production-shaped API skeleton in your chosen stack. This gives Claude a concrete context to reason about routes, validation, and behavior. In the next section, you will collaborate with Claude to plan endpoints and data models, turning this starter into a fully documented service with consistent schemas, tests, and guardrails.
练习题
What is the initial value of the _next_id variable in the in-memory storage initialization?
The _tasks variable in the in-memory storage initialization is a list.
The health check endpoint returns a dictionary with the keys 'status' and '___'.
What is the purpose of the create_task endpoint?
Which of the following are valid HTTP status codes returned by the endpoints in the code?
What happens if a task with a non-existent task_id is requested from the get_task endpoint?
task_id.The put_task endpoint allows partial updates of a task.
The TaskPatch model has optional fields for 'title', 'description', and '___'.
What is the role of the patch_task endpoint?
Which command is used to run the FastAPI application?
python app.pynpm startuvicorn app:app --reloadflask runWhich of the following are required to create a task using curl?
The interactive documentation for the FastAPI application can be accessed at http://localhost:8000/docs.
In the comparison table, FastAPI is described as having a focus on 'strong typing and ___'.
What is the difference between the put_task and patch_task endpoints?
When creating a new task using the FastAPI implementation, which HTTP status code is returned upon successful creation?
Which of the following are valid ways to interact with the TaskFlow API as implemented in FastAPI? (Select all that apply)
The FastAPI implementation of TaskFlow requires manual validation of input data for task creation and updates.
In the FastAPI implementation, the global variable ___ is used to generate unique IDs for new tasks.
What HTTP method and endpoint would you use to partially update an existing task in the TaskFlow FastAPI implementation?
登录后解锁笔记、知识点解析、AI 问答
立即登录