如何使用Node.js和SQLite构建快速且轻量化的API
使用 Node.js 和 SQLite 构建快速轻量化 API 的完整指南
在构建 Web 应用程序时,数据库是存储和管理数据的核心组件之一。在本文中,我们将详细讲解如何使用 Node.js 和 SQLite 创建一个轻量级的 API,用于存储和管理产品信息。
SQLite 是一种无服务器、轻量级的数据库引擎,非常适合中小型 Web 应用程序。它无需复杂的安装和配置,使用简单。Node.js 是一个流行的 JavaScript 运行时环境,常用于构建高效的 Web 应用程序和 API。
环境准备
在开始之前,请确保您的计算机上已安装以下工具:
- Node.js:用于运行 JavaScript 代码。
- npm:Node.js 的包管理工具。
- SQLite:轻量级数据库引擎。
- 文本编辑器或 IDE:推荐使用 Visual Studio Code、Sublime Text 或 Atom。
创建项目并初始化
1. 创建项目目录
首先,为项目创建一个新目录并进入该目录:
mkdir node-sqlite-api
cd node-sqlite-api
2. 初始化 Node.js 项目
在项目目录中运行以下命令,初始化一个新的 package.json 文件:
npm init -y
3. 安装必要的依赖项
安装 Express 和 SQLite3:
npm install express sqlite3
- Express:一个流行的 Node.js Web 框架,用于处理 HTTP 请求和响应。
- sqlite3:SQLite 的 Node.js 驱动程序,用于与 SQLite 数据库交互。
创建 SQLite 数据库
1. 定义数据库架构
在项目目录中创建一个名为 [schema](https://www.explinks.com/blog/ua-what-is-schema-in-database/).sql 的文件,并添加以下内容:
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price REAL NOT NULL
);
此 SQL 脚本将创建一个名为 products 的表,包含以下三列:
id:主键,自动递增。name:产品名称,文本类型。price:产品价格,浮点数类型。
2. 初始化数据库
运行以下命令以创建数据库文件并初始化表结构:
sqlite3 products.db < schema.sql
此命令将在项目目录中生成一个名为 products.db 的 SQLite 数据库文件。
构建 API
1. 创建主文件
在项目目录中创建一个名为 index.js 的文件,并添加以下代码:
// 启动服务器
app.listen(port, () => {
console.log(Server listening on port ${port}.);
});
const app = express();
const port = process.env.PORT || 3000;
// 连接 SQLite 数据库
const db = new sqlite3.Database('./products.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the products database.');
});
app.use(express.json());
// 获取所有产品
app.get('/products', (req, res) => {
db.all('SELECT * FROM products', (err, rows) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal server error');
} else {
res.send(rows);
}
});
});
// 根据 ID 获取单个产品
app.get('/products/:id', (req, res) => {
const { id } = req.params;
db.get('SELECT * FROM products WHERE id = ?', [id], (err, row) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal server error');
} else if (!row) {
res.status(404).send('Product not found');
} else {
res.send(row);
}
});
});
// 添加新产品
app.post('/products', (req, res) => {
const { name, price } = req.body;
if (!name || !price) {
res.status(400).send('Name and price are required');
} else {
const sql = 'INSERT INTO products(name, price) VALUES (?, ?)';
db.run(sql, [name, price], function (err) {
if (err) {
console.error(err.message);
res.status(500).send('Internal server error');
} else {
res.status(201).send({ id: this.lastID, name, price });
}
});
}
});
// 更新产品信息
app.put('/products/:id', (req, res) => {
const { id } = req.params;
const { name, price } = req.body;
if (!name || !price) {
res.status(400).send('Name and price are required');
} else {
const sql = 'UPDATE products SET name = ?, price = ? WHERE id = ?';
db.run(sql, [name, price, id], function (err) {
if (err) {
console.error(err.message);
res.status(500).send('Internal server error');
} else if (this.changes === 0) {
res.status(404).send('Product not found');
} else {
res.status(200).send({ id, name, price });
}
});
}
});
// 删除产品
app.delete('/products/:id', (req, res) => {
const { id } = req.params;
db.run('DELETE FROM products WHERE id = ?', [id], function (err) {
if (err) {
console.error(err.message);
res.status(500).send('Internal server error');
} else if (this.changes === 0) {
res.status(404).send('Product not found');
} else {
res.status(204).send();
}
});
});
// 启动服务器
app.listen(port, () => {
console.log(Server listening on port ${port}.);
});
测试 API
1. 启动服务器
在终端中运行以下命令:
node index.js
服务器将启动并监听 3000 端口。
2. 使用 curl 测试 API
获取所有产品
curl -X GET http://localhost:3000/products
添加新产品
curl -X POST -H 'Content-Type: application/json' -d '{"name": "Product A", "price": 10.99}' http://localhost:3000/products
获取单个产品
curl -X GET http://localhost:3000/products/1
更新产品信息
curl -X PUT -H 'Content-Type: application/json' -d '{"name": "Updated Product", "price": 15.99}' http://localhost:3000/products/1
删除产品
curl -X DELETE http://localhost:3000/products/1
总结
通过本文的步骤,您已经成功创建了一个使用 Node.js 和 SQLite 的轻量级 API。该 API 提供了基本的 CRUD 操作,您可以根据需求进一步扩展功能,例如添加用户认证或复杂查询。
从这里开始,您可以继续学习更多关于 Node.js 和 SQLite 的高级功能,构建更加复杂和强大的应用程序。
原文链接: https://dextrop.medium.com/how-to-build-a-fast-and-lightweight-api-with-node-js-and-sqlite-676cbbec1b6a
最新文章
- 2025年Prompt Chaining:您需要了解的一切 – YourGPT
- api 认证与授权的最佳实践
- 什么是GraphRAG
- 如何获取 Notion 开放平台 API Key 密钥(分步指南)
- DeepSeek-R1 调用 MCP 天气API服务教程:MCP 客户端与服务端入门
- 旅游供应商的Travel Booking APIs [Onix概览]
- 使用 Web Share API 实现图片分享
- 学习与设计rest api的顶级资源
- 十大企业级 API 管理工具全景指南
- Meta×Google 云计算协议:2025 多云/混合云 API 极速落地 AI 出海成本降 40%
- Kimi Chat API入门指南:从注册到实现智能对话
- 5种最佳API认证方法,显著提升…