Tips & Tricks

用 Claude Code 构建 REST API | 初学者实战入门指南

与 Claude Code 一起学习 REST API 基础。从端点设计到数据验证、错误处理,全部提供可直接复制运行的代码。

“不知道 REST API 该从哪里开始”——我最初也是这样。

看文档太过抽象,根本搞不清楚到底要做什么。后来我开始用 Claude Code,发现**“先做出能跑的东西,边做边学”**才是最快的方法。

这篇文章将带你从零 REST API 基础,到实际做出一个可运行的 API——全程与 Claude Code 一起完成。所有代码都可以直接复制粘贴运行。


REST API 是什么?(三行总结)

REST API 是通过 HTTP 操作 Web 上资源(数据)的一套规范

浏览器/App  →  HTTP 请求  →  服务器 (API)
            ←  JSON 响应  ←

以用户管理 API 为例:

操作HTTP 方法URL
获取用户列表GET/users
获取特定用户GET/users/123
创建用户POST/users
更新用户PUT/users/123
删除用户DELETE/users/123

理解这些之后,就可以和 Claude Code 一起开始构建了。


环境搭建

我们使用 Hono(轻量级 TypeScript Web 框架)。它比 Express 更具类型安全性,与 Claude Code 配合也非常顺畅。

mkdir my-first-api
cd my-first-api
npm init -y
npm install hono
npm install -D typescript @types/node ts-node
npx tsc --init

创建 src/index.ts,然后问 Claude Code:

claude -p "
用 Hono 在 src/index.ts 里创建一个 REST API 模板。
- 在 3000 端口启动服务器
- 添加用于健康检查的 GET /health 端点
- 返回 JSON 格式的响应
运行命令:npx ts-node src/index.ts
"

Claude Code 会生成类似这样的代码:

// src/index.ts
import { Hono } from "hono";
import { serve } from "@hono/node-server";

const app = new Hono();

app.get("/health", (c) => {
  return c.json({ status: "ok", timestamp: new Date().toISOString() });
});

serve({ fetch: app.fetch, port: 3000 }, () => {
  console.log("Server running at http://localhost:3000");
});
npx ts-node src/index.ts
# → Server running at http://localhost:3000

curl http://localhost:3000/health
# → {"status":"ok","timestamp":"2026-04-27T07:30:00.000Z"}

跑起来了吗?这就是 REST API 的起点。


Step 1:构建基本的 CRUD

接下来,我们来做一个管理 Todo 列表的 API。让 Claude Code 帮忙:

claude -p "
在 src/index.ts 中添加 Todo 的 CRUD 端点。
- GET  /todos         — 获取列表
- GET  /todos/:id     — 获取单条
- POST /todos         — 创建(title: string 必填)
- PUT  /todos/:id     — 更新(title: string)
- DELETE /todos/:id   — 删除

用内存数组管理数据。
Todo 类型:{ id: string, title: string, done: boolean, createdAt: string }
用 crypto.randomUUID() 生成 id
"

生成的代码:

import { Hono } from "hono";
import { serve } from "@hono/node-server";

const app = new Hono();

// 内存数据存储
type Todo = { id: string; title: string; done: boolean; createdAt: string };
let todos: Todo[] = [];

// 获取列表
app.get("/todos", (c) => c.json(todos));

// 获取单条
app.get("/todos/:id", (c) => {
  const todo = todos.find((t) => t.id === c.req.param("id"));
  if (!todo) return c.json({ error: "Not found" }, 404);
  return c.json(todo);
});

// 创建
app.post("/todos", async (c) => {
  const body = await c.req.json();
  if (!body.title) return c.json({ error: "title is required" }, 400);
  const todo: Todo = {
    id: crypto.randomUUID(),
    title: body.title,
    done: false,
    createdAt: new Date().toISOString(),
  };
  todos.push(todo);
  return c.json(todo, 201);
});

// 更新
app.put("/todos/:id", async (c) => {
  const idx = todos.findIndex((t) => t.id === c.req.param("id"));
  if (idx === -1) return c.json({ error: "Not found" }, 404);
  const body = await c.req.json();
  todos[idx] = { ...todos[idx], ...body };
  return c.json(todos[idx]);
});

// 删除
app.delete("/todos/:id", (c) => {
  const idx = todos.findIndex((t) => t.id === c.req.param("id"));
  if (idx === -1) return c.json({ error: "Not found" }, 404);
  todos.splice(idx, 1);
  return c.json({ message: "Deleted" });
});

serve({ fetch: app.fetch, port: 3000 }, () => {
  console.log("Server running at http://localhost:3000");
});

来测试一下:

# 创建 Todo
curl -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{"title": "尝试 Claude Code"}'

# 获取列表
curl http://localhost:3000/todos

# 删除(使用上面返回的 id)
curl -X DELETE http://localhost:3000/todos/<id>

Step 2:添加数据验证

“空 title 也能创建""任何字符串都可以当 ID 访问”——这些问题都可以通过验证来防止。让 Claude Code 来帮忙:

claude -p "
用 zod 为 POST /todos 和 PUT /todos/:id 添加验证。
- title:1 到 100 个字符的字符串
- done:(仅 PUT)boolean
验证失败时返回 400 错误和具体的错误消息
"
npm install zod

Claude Code 添加 zod schema:

import { z } from "zod";

const CreateTodoSchema = z.object({
  title: z.string().min(1, "标题至少需要 1 个字符").max(100, "标题不能超过 100 个字符"),
});

const UpdateTodoSchema = z.object({
  title: z.string().min(1).max(100).optional(),
  done: z.boolean().optional(),
});

// POST /todos(带验证)
app.post("/todos", async (c) => {
  const body = await c.req.json().catch(() => ({}));
  const result = CreateTodoSchema.safeParse(body);
  if (!result.success) {
    return c.json({ error: result.error.flatten().fieldErrors }, 400);
  }
  const todo: Todo = {
    id: crypto.randomUUID(),
    title: result.data.title,
    done: false,
    createdAt: new Date().toISOString(),
  };
  todos.push(todo);
  return c.json(todo, 201);
});

验证错误的确认:

# 不带 title 创建 → 应该报错
curl -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{}'
# → {"error":{"title":["标题至少需要 1 个字符"]}}

Step 3:统一错误处理

现在每个端点的错误格式各不相同。让 Claude Code 统一一下:

claude -p "
统一错误处理。
- 通用错误响应格式:{ error: { code: string, message: string } }
- 404: NOT_FOUND
- 400: VALIDATION_ERROR
- 500: INTERNAL_SERVER_ERROR
用 Hono 的 onError 实现全局错误处理器
"
// 错误类型定义
class AppError extends Error {
  constructor(
    public code: string,
    public message: string,
    public statusCode: number = 400
  ) {
    super(message);
  }
}

// 全局错误处理器
app.onError((err, c) => {
  if (err instanceof AppError) {
    return c.json(
      { error: { code: err.code, message: err.message } },
      err.statusCode as any
    );
  }
  console.error(err);
  return c.json(
    { error: { code: "INTERNAL_SERVER_ERROR", message: "发生了意外错误" } },
    500
  );
});

// 使用方法
app.get("/todos/:id", (c) => {
  const todo = todos.find((t) => t.id === c.req.param("id"));
  if (!todo) throw new AppError("NOT_FOUND", "找不到指定的 Todo", 404);
  return c.json(todo);
});

Step 4:自动生成 Swagger UI 文档

API 做完之后还需要文档。让 Claude Code 几分钟内搞定:

claude -p "
用 @hono/swagger-ui 和 @hono/zod-openapi
在 /docs 添加 Swagger UI。
为现有端点添加 OpenAPI schema
"
npm install @hono/swagger-ui @hono/zod-openapi

完成后访问 http://localhost:3000/docs 即可看到 API 文档。


与 Claude Code 一起开发 API 的流程(总结)

这是我实际使用的开发流程:

1. 告诉 Claude Code "我需要这样的 API"
    ↓
2. 确认生成的代码,测试是否运行正常
    ↓
3. 对话调整:"修改这里""添加验证"
    ↓
4. 测试通过后 git commit

我最初踩的坑(亲身经历)

我做第一个 API 时,把错误处理全部省略了,后来补加花了很多时间。现在我一开始就加上”也包含错误处理”这句话,生成的代码就很完整。和 Claude Code 合作的诀窍是一开始就把所有需求一起说清楚


常见的 3 个陷阱

陷阱 1:忽略 JSON 解析错误

// ❌ 出错了也不知道
const body = await c.req.json();

// ✅ 捕获解析失败
const body = await c.req.json().catch(() => null);
if (!body) return c.json({ error: "Invalid JSON" }, 400);

陷阱 2:混淆 404 和 400

400:请求本身有问题(验证错误、缺少必填字段)
404:资源不存在(找不到 ID)
422:请求格式正确但无法处理

问 Claude Code “这里应该返回 404 还是 400?“它会给出正确判断。

陷阱 3:全部存在内存里

本文的代码用内存数组只是为了演示。重启服务器后数据会消失。正式环境需要 PostgreSQL 或 MongoDB 这样的数据库。告诉 Claude Code “改成存到 SQLite 而不是内存”,它就会帮你迁移。


下一步

掌握了 REST API 基础之后,可以尝试以下内容:

步骤内容
数据库集成SQLite → PostgreSQL(Prisma)
认证添加 JWT token 认证
测试用 vitest 写 API 测试
部署发布到 Vercel / Cloudflare Workers

这些都只需要对 Claude Code 说”添加○○“,几分钟内就能出基础代码。先做出能运行的东西——这才是最快的捷径。

相关文章

#claude-code #rest-api #beginner #typescript #backend #tutorial

让你的 Claude Code 工作流更上一层楼

50 个经过实战检验的提示词模板,现在就能复制粘贴到 Claude Code 中使用。

免费

免费 PDF:5 分钟看懂 Claude Code 速查表

只需留下邮箱,我们就会立即把这份 A4 一页速查表 PDF 发送给你。

我们会严格保护你的个人信息,绝不发送垃圾邮件。

Masa

本文作者

Masa

深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。