引言:为什么用C++开发REST API?
C++传统上与系统编程、游戏和高负载应用相关联。然而,现代C++(C++17和C++20标准)结合轻量级库,使您能够创建快速高效的Web服务。如果您需要一个每秒处理数千个请求且延迟极低的REST API,C++是一个绝佳的选择。
在本文中,我们将使用Crow库在30分钟内用C++创建一个功能完善的REST API。这是一个类似于Python Flask但用C++编写的迷你框架。我们将设置路由,学习解析JSON,并返回响应。
第一步:环境设置与安装Crow
我们需要一个支持C++17的编译器(GCC 7+、Clang 5+、MSVC 2019+)以及一个依赖管理器,如vcpkg或Conan。最简单的方法是将Crow作为仅头文件下载。
1.1 通过vcpkg安装(推荐)
如果您已经安装了vcpkg,请运行以下命令:
vcpkg install crow
然后,在编译时指定库的路径:
g++ main.cpp -std=c++17 -I/path/to/vcpkg/installed/x64-linux/include -lpthread -o server
1.2 手动安装(仅头文件)
从GitHub下载最新版本的Crow。您只需要crow_all.h文件(一体式)。将其放入您的项目文件夹中。
第二步:创建具有两个端点的简单服务器
让我们编写一个最小服务器,监听8080端口并响应GET和POST请求。创建一个main.cpp文件。
2.1 基本服务器代码
#include "crow_all.h"
int main() {
crow::SimpleApp app;
// GET端点:根页面
CROW_ROUTE(app, "/")([](){
return "Hello, REST API on C++!";
});
// GET端点:/api/status
CROW_ROUTE(app, "/api/status")([](){
crow::json::wvalue response;
response["status"] = "ok";
response["message"] = "Server is running";
return response;
});
app.port(8080).multithreaded().run();
}
编译并运行:
g++ main.cpp -std=c++17 -lpthread -o api_server
./api_server
现在在浏览器中访问http://localhost:8080/api/status — 您将看到一个JSON响应。
第三步:处理JSON和处理POST请求
真正的REST API需要接收来自客户端的数据。让我们学习如何在请求体中接受JSON。
3.1 用于创建用户的POST端点
#include "crow_all.h"
#include <string>
#include <unordered_map>
int main() {
crow::SimpleApp app;
// 简单的内存存储(用于演示)
std::unordered_map<int, std::string> users;
int next_id = 1;
// POST /api/users — 创建用户
CROW_ROUTE(app, "/api/users").methods("POST"_method)([&](const crow::request& req){
auto body = crow::json::load(req.body);
if (!body || !body.has("name")) {
return crow::response(400, "Missing 'name' field");
}
std::string name = body["name"].s();
int id = next_id++;
users[id] = name;
crow::json::wvalue response;
response["id"] = id;
response["name"] = name;
return crow::response(201, response);
});
// GET /api/users/{id} — 获取用户
CROW_ROUTE(app, "/api/users/<int>")([&](int id){
auto it = users.find(id);
if (it == users.end()) {
return crow::response(404, "User not found");
}
crow::json::wvalue response;
response["id"] = id;
response["name"] = it->second;
return crow::response(respon