Hello World - REST API 操作数据库

知识库
知识库文档
/tech-stacks/couchdb/examples/Hello World - REST API 操作数据库.md

文档

CouchDB Hello World:REST API 操作数据库

目标

通过 CouchDB 的 HTTP REST API 创建数据库、插入 JSON 文档、查询和更新,理解其纯 HTTP 操作范式。

完整代码

使用 curl(无需任何驱动)

# 1. 创建数据库
curl -X PUT http://admin:password@localhost:5984/library

# 2. 插入文档(POST 自动生成 _id)
curl -X POST http://admin:password@localhost:5984/library \
  -H "Content-Type: application/json" \
  -d '{
    "title": "深入理解计算机系统",
    "author": "Randal E. Bryant",
    "year": 2015,
    "pages": 1080,
    "tags": ["cs", "systems", "textbook"] 
  }'

# 返回: {"ok":true,"id":"<uuid>","rev":"1-xxx"}

# 3. 指定 _id 插入
curl -X PUT http://admin:password@localhost:5984/library/book_001 \
  -H "Content-Type: application/json" \
  -d '{  
    "title": "算法导论",
    "author": "Thomas H. Cormen",
    "year": 2009,
    "pages": 1312,
    "tags": ["algorithms", "textbook"]
  }'

# 返回: {"ok":true,"id":"book_001","rev":"1-xxx"}

# 4. 获取文档
curl http://admin:password@localhost:5984/library/book_001

# 5. 更新文档(必须带当前 _rev)
curl -X PUT http://admin:password@localhost:5984/library/book_001 \
  -H "Content-Type: application/json" \
  -d '{
    "_rev": "1-xxx",
    "title": "算法导论(第3版)",
    "author": "Thomas H. Cormen",
    "year": 2009,
    "pages": 1312,
    "tags": ["algorithms", "textbook", "bestseller"]
  }'

# 6. 删除文档
curl -X DELETE http://admin:password@localhost:5984/library/book_001?rev=<当前_rev>

# 7. 查询全部文档
curl http://admin:password@localhost:5984/library/_all_docs?include_docs=true

Python 版本

# pip install couchdb
import couchdb

# 连接服务器
server = couchdb.Server('http://admin:password@localhost:5984/')

# 创建数据库
db = server.create('library')

# 插入文档
doc_id, rev = db.save({
    'title': '深入理解计算机系统',
    'author': 'Randal E. Bryant',
    'year': 2015,
    'pages': 1080,
    'tags': ['cs', 'systems', 'textbook']
})
print(f"保存成功: id={doc_id}, rev={rev}")

# 查询
doc = db[doc_id]
print(f"书名: {doc['title']}")

# 使用 Mango 查询(需要先创建索引)
db.create_index(['author'])
results = db.find({'selector': {'author': 'Randal E. Bryant'}})
for row in results:
    print(row)

# 更新
doc['pages'] = 1100
db.save(doc)

# 删除
db.delete(doc)

预期输出

// POST 创建文档返回
{"ok":true,"id":"abc123...","rev":"1-xxx"}

// GET 获取文档返回
{
  "_id": "book_001",
  "_rev": "2-yyy",
  "title": "算法导论(第3版)",
  "author": "Thomas H. Cormen",
  "year": 2009,
  "pages": 1312,
  "tags": ["algorithms", "textbook", "bestseller"]
}

关键点

  • CouchDB 一切操作皆 HTTP,无需 SQL
  • 每次更新需要提供 _rev(乐观锁机制)
  • _all_docs 返回所有文档,include_docs=true 包含完整内容

信息

路径
/tech-stacks/couchdb/examples/Hello World - REST API 操作数据库.md
更新时间
2026/5/31