Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Claude Code in Action

Claude Code in Action

This chapter, from opening the terminal to getting a complete Todo REST API running, is driven throughout by Claude Code + DeepSeek V4.

Claude Code + DeepSeek V4 configuration reference:Claude Code DeepSeek Configuration

Let's first look at Claude Code's basic operation interface and common high-frequency commands.

Start your first Claude Code session

Open a terminal, enter any working directory (or create a new empty folder), then type:



$ mkdir runoob-todo-api

$ cd runoob-todo-api

$ claude

On first launch, you'll see the welcome screen, version information, and DeepSeek's environment variable configuration.

If you're not sure whether the configuration took effect, immediately after entering type /status, confirming that the Base URL points to https://api.deepseek.com/anthropic。

Common slash command quick reference

In Claude Code's dialog, those starting with / are built-in commands and are not sent to the model.

Command Purpose
/status View the current model, Base URL, and session statistics
/help Show all available commands
/clear Clear the current conversation context (does not delete files)
/exit or Ctrl+C Exit Claude Code
/undo Undo the last file modification
/diff View the git diff of the most recent changes

Permission prompt mechanism

When Claude Code is about to write a file or execute a command, it pauses first, lists the operations it will perform, and waits for your confirmation.

This is Claude Code's most important security mechanism; beginners need not worry about the AI making changes out of control.

You'll see a prompt like this:



┌─────────────────────────────────────────────────┐

│  Claude wants to create the following files:     │

│                                                  │

│  • src/index.js                                  │

│  • src/routes/todos.js                           │

│  • package.json                                  │

│                                                  │

│  Allow? [Y/n]                                    │

└─────────────────────────────────────────────────┘

Press Enter directly or type y to confirm, type n to skip.


Practical project: Build a Todo API from scratch with AI

This section guides you to use natural language to drive Claude Code and generate a runnable Node.js REST API from scratch.

Project goal

We're going to build a REST API with the following features:

an interface Function
GET /todos Get all todos
POST /todos Create a new todo
PUT /todos/:id Update a todo (mark complete / modify content)
DELETE /todos/:id Delete a todo

Tech stack: Node.js + Express, data temporarily stored in memory (no database needed, reducing complexity).

Step 1: Describe requirements in natural language

Type the following in Claude Code's dialog (just copy and paste):



请帮我从零创建一个 Node.js + Express 的 Todo REST API 项目。



要求:

- 支持 GET /todos、POST /todos、PUT /todos/:id、DELETE /todos/:id 四个接口

- 数据先存在内存数组里,不需要数据库

- 每个 todo 包含:id、title、completed(布尔值)、createdAt 字段

- 请求和响应都使用 JSON 格式

- 加上基础的错误处理(404、400 等)

- 生成一份 README.md,说明如何启动和测试接口



Project structure suggestions:

my-todo-api/

├── src/

│   ├── index.js       # 入口文件

│   └── routes/

│       └── todos.js   # Todo 路由

├── package.json

└── README.md

Three elements of a well-written prompt:Context(tell the AI the tech stack and project background),Constraint(clearly state what you don't want),Expected output(give specific file structure or format requirements).

Step 2: Claude Code generates the file structure

After confirming permissions, Claude Code creates the following files in sequence.

During generation, there are many permission confirmations; generally just choose Yes:

After success, the following information is output, including generated content, startup info, etc., in great detail:

Let's look at the generated project structure:

package.json

Example

{

 

"name"

:

"my-todo-api"

,

 

"version"

:

"1.0.0"

,

 

"description"

:

"A simple Todo REST API built with Express"

,

 

"main"

:

"src/index.js"

,

 

"scripts"

:

{

   

"start"

:

"node src/index.js"

,

   

"dev"

:

"nodemon src/index.js"

 

}

,

 

"dependencies"

:

{

   

"express"

:

"^4.18.2"

 

}

,

 

"devDependencies"

:

{

   

"nodemon"

:

"^3.0.1"

 

}

}

src/index.js (entry file)

Example

// File path: src/index.js

// Todo API entry file, responsible for Express app configuration and startup

const

express

=

require

(

'express'

)

;

const

todosRouter

=

require

(

'./routes/todos'

)

;

const

app

=

express

(

)

;

// Port number: prefer the environment variable PORT, default 3000

const

PORT

=

process.

env

.

PORT

||

3000

;

// Middleware: parse the JSON request body (required, otherwise req.body is undefined)

app.

use

(

express.

json

(

)

)

;

// Register the Todo routes; all requests to /todos paths are handled by todosRouter

app.

use

(

'/todos'

,

todosRouter

)

;

// Root path: return the welcome message and version number

app.

get

(

'/'

,

(

req

,

res

)

=>

{

  res.

json

(

{

message

:

'Todo API is running!'

,

version

:

'1.0.0'

}

)

;

}

)

;

// Global error-handling middleware (required, catches unhandled exceptions)

app.

use

(

(

err

,

req

,

res

,

next

)

=>

{

  console.

error

(

err.

stack

)

;

  res.

status

(

500

)

.

json

(

{

error

:

'Internal Server Error'

}

)

;

}

)

;

// Start the HTTP server

app.

listen

(

PORT

,

(

)

=>

{

  console.

log

(

`Server is running on http

:

//localhost:${PORT}`);

}

)

;

src/routes/todos.js (core route file)

Example

// File path: src/routes/todos.js

// Todo route module, containing complete CRUD business logic

const

express

=

require

(

'express'

)

;

const

router

=

express.

Router

(

)

;

// In-memory storage: use an array to simulate a database

// Data is lost after the server restarts; it can later be replaced with a persistence solution like SQLite

let todos

=

[

]

;

// Auto-increment ID counter

let nextId

=

1

;

// GET /todos — get all todos

router.

get

(

'/'

,

(

req

,

res

)

=>

{

  res.

json

(

todos

)

;

}

)

;

// POST /todos — create a new todo

router.

post

(

'/'

,

(

req

,

res

)

=>

{

 

const

{

title

}

=

req.

body

;

 

// Parameter validation: title is a required field, must be a string and not empty

 

if

(

!

title

||

typeof

title

!==

'string'

||

title.

trim

(

)

===

''

)

{

   

return

res.

status

(

400

)

.

json

(

{

error

:

'title field cannot be empty'

}

)

;

 

}

 

// Build a new todo object

 

const

newTodo

=

{

    id

:

nextId

++,

                       

// Auto-increment ID

    title

:

title.

trim

(

)

,

                 

// remove leading and trailing spaces

    completed

:

false

,

                     

// Newly created todos are incomplete by default

    createdAt

:

new

Date

(

)

.

toISOString

(

)

,

 

// ISO 8601 format timestamp

 

}

;

  todos.

push

(

newTodo

)

;

 

// 201 Created indicates the resource was created successfully

  res.

status

(

201

)

.

json

(

newTodo

)

;

}

)

;

// PUT /todos/:id — update a todo

router.

put

(

'/:id'

,

(

req

,

res

)

=>

{

 

// Convert the path parameter from a string to a number

 

const

id

=

parseInt

(

req.

params

.

id

)

;

 

const

todo

=

todos.

find

(

t

=>

t.

id

===

id

)

;

 

// 404: resource not found

 

if

(

!

todo

)

{

   

return

res.

status

(

404

)

.

json

(

{

error

:

`Todo with id $

{

id

}

not found`

}

)

;

 

}

 

const

{

title

,

completed

}

=

req.

body

;

 

// Only update the fields that were passed in; those not passed keep their original values

 

if

(

title

!==

undefined

)

todo.

title

=

title.

trim

(

)

;

 

// Boolean() ensures completed is always a boolean

 

if

(

completed

!==

undefined

)

todo.

completed

=

Boolean

(

completed

)

;

  res.

json

(

todo

)

;

}

)

;

// DELETE /todos/:id — delete a todo

router.

delete

(

'/:id'

,

(

req

,

res

)

=>

{

 

const

id

=

parseInt

(

req.

params

.

id

)

;

 

const

index

=

todos.

findIndex

(

t

=>

t.

id

===

id

)

;

 

if

(

index

===

1

)

{

   

return

res.

status

(

404

)

.

json

(

{

error

:

`Todo with id $

{

id

}

not found`

}

)

;

 

}

 

// Remove the element at the specified position from the array

  todos.

splice

(

index

,

1

)

;

 

// 204 No Content indicates successful deletion, with an empty response body

  res.

status

(

204

)

.

send

(

)

;

}

)

;

module.

exports

=

router

;

Step 3: Review and confirm changes

After Claude Code generates code, don't rush to run it directly; develop the habit of reviewing.

You can continue asking follow-up questions in the conversation:



I looked at the code you generated for me, and I have a few questions I want to confirm:

1. POST /todos 时,如果 title 是数字类型会怎么处理?

2. PUT 接口能同时更新 title 和 completed 吗?

3. 有没有对 id 不是数字的情况做处理?

Claude Code will answer one by one and can fix the code on the spot.

This "generate → question → fix" cycle is the core rhythm of collaborating with AI.

Step 4: Install dependencies and start the server

Type in Claude Code's dialog:



请帮我安装依赖并启动项目,然后告诉我怎么用 curl 测试每个接口

Claude Code performs the following operations (each step requests your confirmation).

Install dependencies



$ npm install

Example output:



added 64 packages in 2.3s

Start the service



$ npm start

Output:



Server is running on http://localhost:3000

Test commands

Open a new terminal window and run the following curl commands in sequence:



# Create the first Todo

$ curl -X POST http://localhost:3000/todos \

  -H "Content-Type: application/json" \

  -d '{"title": "学习 Claude Code"}'



# Create the second Todo

$ curl -X POST http://localhost:3000/todos \

  -H "Content-Type: application/json" \

  -d '{"title": "完成 DeepSeek 配置"}'



# Get all Todos

$ curl http://localhost:3000/todos



# Mark the first one as complete

$ curl -X PUT http://localhost:3000/todos/1 \

  -H "Content-Type: application/json" \

  -d '{"completed": true}'



# Delete the second one

$ curl -X DELETE http://localhost:3000/todos/2



# Check the list again to confirm successful deletion

$ curl http://localhost:3000/todos

Expected output (final result of GET /todos)



[

  {

    "id": 1,

    "title": "学习 Claude Code",

    "completed": true,

    "createdAt": "2026-05-20T10:30:00.000Z"

  }

]

Congratulations, your first AI-assisted developed API is up and running.

Advanced challenge: Let Claude Code help you add new features

After the API is running, try using natural language to have Claude Code extend the features:



Please add the following features to the Todo API:

1. GET /todos 支持 ?completed=true/false 的查询参数过滤

2. GET /todos 支持 ?sort=createdAt&order=desc 的排序参数

3. 同时更新 README.md 里的接口文档

Observe how Claude Code understands the existing code structure and precisely inserts new logic at the right place, rather than rewriting the entire file.

This is exactly where it's stronger than ordinary code generation tools.


CLAUDE.md: project memory file

CLAUDE.md is Claude Code's project-level memory file, letting the AI automatically understand project conventions on every startup.

Why is it needed

Every time Claude Code starts, it's "brand new" — it doesn't remember what was said in the last session.

But if the project root has a CLAUDE.md file, Claude Code automatically reads it on every startup, which is like giving the AI a "project manual".

Pain points without CLAUDE.md:

CLAUDE.md writing template

Create CLAUDE.md in the project root, referring to the following template:



# Project Description (CLAUDE.md)



## Project Overview

这是一个 Node.js + Express 的 Todo REST API 项目。

当前阶段:数据存在内存中,下一步会迁移到 SQLite。



## 技术栈

- 运行时:Node.js 18+

- 框架:Express 4.x

- 测试:(暂无,后续加 Jest)

- 代码风格:ESLint + Prettier(配置见 .eslintrc)



## Directory Structure

src/

├── index.js        # 入口,只做 app 配置和监听

└── routes/

    └── todos.js    # Todo 业务逻辑全在这里



## 命名规范

- 文件名:kebab-case(如 todo-service.js)

- 变量/函数:camelCase

- 常量:UPPER_SNAKE_CASE

- 路由文件按资源名命名(如 users.js、products.js)



## Important Conventions

- 所有接口返回 JSON,错误统一格式:{ "error": "错误描述" }

- HTTP 状态码语义要准确:创建成功用 201,删除成功用 204

- 禁止在路由文件里直接操作数据库(现在是内存数组,将来是 DB)

- 每个路由文件只处理一种资源



## Prohibited Items

- 不要用 var,只用 const/let

- 不要用回调风格,统一用 async/await

- 不要在代码里写中文注释(英文注释即可)

- 不要安装 lodash,原生 JS 方法够用



## Startup method

npm start          # 生产模式

npm run dev        # 开发模式(nodemon 热重载)



## 测试接口

见 README.md 的 curl 示例

Let Claude Code automatically generate CLAUDE.md

Don't want to write it by hand? Just let the AI generate it for you:



请根据当前项目的代码结构和我们的对话记录,

帮我生成一份 CLAUDE.md 文件,

内容包括项目概述、技术栈、目录结构、命名规范和重要约定。

Claude Code analyzes all generated files and automatically organizes a CLAUDE.md suited to this project.

CLAUDE.md maintenance rhythm

Timing To-do list
Introduce a new dependency Update the "Tech Stack" section
Change the file structure Update the "Directory Structure" section
Establish new coding standards Append to "Important Conventions"
Find the AI repeatedly making the same mistake Add to "Prohibited Items"

Commit CLAUDE.md to Git, and all team members and the AI share the same conventions.

This is the infrastructure for AI-assisted team collaboration.


Chapter Summary

What you learned Corresponding content
Start Claude Code and confirm the DeepSeek configuration Start a session and /status
Describe requirements with a three-element prompt Step 1: Natural language description
Review AI-generated code Step 3: Review and question
Install dependencies, start, and test the API with curl Step 4: Run and test
Manage project memory with CLAUDE.md CLAUDE.md configuration