正在学习

14.3 Backend and API Prompts (1)

14.3 Backend and API Prompts (1)

Backend and API development is one of the strongest applications of Claude Code. Unlike traditional code generators that focus on boilerplate, Claude understands intent, logic flow, and architectural design. It can generate full backend modules, RESTful endpoints, and middleware pipelines while keeping your business logic clean and maintainable.

This section focuses on how to write effective backend prompts — prompts that produce working API servers, handle data validation, integrate databases, and manage error handling. Whether you’re working with FastAPI, Express.js, Flask, or Django, the goal is to show how Claude can assist in building production-grade backend systems through well-structured, context-rich requests.

Concept Development

Backend prompts differ from frontend prompts in one key way: they require precision in structure and functionality rather than aesthetics. Claude performs best when you provide:

  • The framework and programming language (e.g., “Python + FastAPI”).
  • The purpose of the API (e.g., “user authentication” or “task management”).
  • The requirements such as authentication, validation, or database connection.
  • The format of the expected output — a single module, multiple routes, or an entire service.
  • The environment constraints— whether it should use async functions, follow REST principles, or integrate with CI/CD tools.

By defining these clearly, you guide Claude to produce structured, testable, and deployable backend systems rather than generic snippets.

Hands-On Example 1: FastAPI CRUD Application

Prompt:

You are a senior Python backend engineer.

Build a FastAPI application for managing tasks with endpoints to:

  • Create, read, update, and delete tasks

  • Validate request bodies using Pydantic

  • Include exception handling for missing tasks

Return the complete runnable Python file.

Claude Output (Example):

from fastapi import FastAPI, HTTPException

from pydantic import BaseModel

from typing import List

app = FastAPI()

class Task(BaseModel):

id: int

title: str

completed: bool = False

tasks: List[Task] = []

@app.post("/tasks", response_model=Task)

def create_task(task: Task):

tasks.append(task)

return task

@app.get("/tasks", response_model=List[Task])

def get_tasks():

return tasks

@app.get("/tasks/{task_id}", response_model=Task)

def get_task(task_id: int):

for task in tasks:

if task.id == task_id:

return task

raise HTTPException(status_code=404, detail="Task not found")

@app.put("/tasks/{task_id}", response_model=Task)

def update_task(task_id: int, updated_task: Task):

for i, task in enumerate(tasks):

if task.id == task_id:

tasks[i] = updated_task

return updated_task

raise HTTPException(status_code=404, detail="Task not found")

@app.delete("/tasks/{task_id}")

def delete_task(task_id: int):

for i, task in enumerate(tasks):

if task.id == task_id:

tasks.pop(i)

return {"detail": "Task deleted"}

raise HTTPException(status_code=404, detail="Task not found")

Why It Works: The prompt specifies the framework, data validation, and error handling, allowing Claude to produce a complete, functional FastAPI app — no incomplete placeholders, no missing imports. The result runs directly with uvicorn main:app --reload.

Hands-On Example 2: Node.js Express API with Middleware

Prompt:

Create a Node.js Express API that manages user authentication.

Include:

  • Endpoints for register and login

  • Password hashing using bcrypt

  • Token generation using JWT

  • Middleware to protect private routes

Return one complete file ready to run.

Claude Output (Example):

import express from "express";

import bcrypt from "bcryptjs";

import jwt from "jsonwebtoken";

const app = express();

app.use(express.json());

const users = [];

const SECRET = "mysecretkey";

app.post("/register", async (req, res) => {

const { username, password } = req.body;

const hashed = await bcrypt.hash(password, 10);

users.push({ username, password: hashed });

res.status(201).json({ message: "User registered successfully" });

});

app.post("/login", async (req, res) => {

const { username, password } = req.body;

const user = users.find((u) => u.username === username);

if (!user) return res.status(404).json({ message: "User not found" });

const valid = await bcrypt.compare(password, user.password);

if (!valid) return res.status(401).json({ message: "Invalid credentials" });

const token = jwt.sign({ username }, SECRET, { expiresIn: "1h" });

res.json({ token });

});

function auth(req, res, next) {

const authHeader = req.headers.authorization;

if (!authHeader) return res.status(401).json({ message: "Missing token" });

try {

const decoded = jwt.verify(authHeader.split(" ")[1], SECRET);

req.user = decoded;

next();

} catch {

res.status(401).json({ message: "Invalid token" });

}

}

app.get("/profile", auth, (req, res) => {

res.json({ message: `Welcome ${req.user.username}!` });

});

app.listen(4000, () => console.log("Server running on port 4000"));

Key Takeaways:

  • The prompt defines security mechanisms (JWT, bcrypt) and specific routes, ensuring completeness.
  • Claude correctly includes middleware and authentication logic, which is often missing in generic AI code.
  • The output runs without modification using node app.js (after installing dependencies).

Hands-On Example 3: Flask API with Database Integration

Prompt:

Build a Flask REST API for a book catalog.

Include:

  • SQLite database integration

  • SQLAlchemy ORM models

  • CRUD routes for books

  • Error handling for invalid operations

Return a complete runnable Python script.

Claude Output (Example):

from flask import Flask, request, jsonify

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///books.db"

db = SQLAlchemy(app)

class Book(db.Model):

id = db.Column(db.Integer, primary_key=True)

title = db.Column(db.String(100), nullable=False)

author = db.Column(db.String(100), nullable=False)

@app.before_first_request

def create_tables():

db.create_all()

@app.route("/books", methods=["POST"])

def add_book():

data = request.get_json()

book = Book(title=data["title"], author=data["author"])

db.session.add(book)

db.session.commit()

练习题

When writing backend prompts for Claude, which of the following is NOT a key requirement?

A. The framework and programming language
B. The purpose of the API
C. The color scheme for the user interface
D. The format of the expected output

Which of the following are features of a well-structured FastAPI CRUD application prompt?

A. Endpoints for CRUD operations
B. Data validation using Pydantic
C. Middleware for authentication
D. Exception handling for missing tasks

A Node.js Express API prompt should include endpoints for user registration and login, password hashing using bcrypt, and token generation using JWT.

In a FastAPI application, the ___ model is used to validate request bodies for tasks.

Explain why specifying the framework and data validation in a backend prompt is important.

Which of the following is a key aspect of effective documentation generation by Claude?

A. The color scheme of the documentation
B. The documentation format
C. The number of code snippets
D. The size of the images used

Which of the following are types of documentation Claude can produce?

A. Inline code comments
B. API reference pages
C. User interface designs
D. Full Markdown-based developer guides

The goal of documentation generation by Claude is to make documentation an afterthought in the development process.

In a Node.js Express API, ___ is used for password hashing to ensure secure user authentication.

What is the purpose of including exception handling in a FastAPI CRUD application prompt?

Which of the following is a benefit of using Claude for backend development?

A. It focuses on generating boilerplate code
B. It understands intent, logic flow, and architectural design
C. It only works with frontend frameworks
D. It generates incomplete and untestable code

Which of the following are components of a Flask API prompt for a book catalog?

A. SQLite database integration
B. SQLAlchemy ORM models
C. CRUD routes for books
D. User interface designs

Claude's approach to documentation generation makes it suitable for producing living documentation that evolves with the codebase.

In a FastAPI application, the ___ exception is raised when a task is not found.

What is the role of middleware in a Node.js Express API for user authentication?

When creating a backend prompt for a FastAPI application that manages user profiles, which of the following is a critical requirement to ensure Claude generates a complete and functional application?

A. The prompt should specify the frontend framework to be used alongside FastAPI.
B. The prompt should include the framework (FastAPI), the purpose (user profile management), and requirements such as authentication and database connection.
C. The prompt should only mention the purpose (user profile management) and leave other details for Claude to decide.
D. The prompt should focus on the aesthetics of the API endpoints rather than their functionality.

Which of the following are essential components to include in a prompt for a Node.js Express API that handles user authentication with JWT tokens?

A. Endpoints for user registration and login
B. Password hashing using bcrypt
C. Token generation using JWT
D. Middleware to protect private routes
E. Specification of the frontend framework to be used

A well-structured prompt for a Flask REST API that manages a book catalog should include SQLite database integration, SQLAlchemy ORM models, CRUD routes for books, and error handling for invalid operations to ensure Claude generates a complete and runnable script.

登录后解锁笔记、知识点解析、AI 问答

立即登录