如何在30分钟内用C++编写REST API:实战指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

介绍:为什么要在C++上编写REST API?



REST API(Representational State Transfer)是一种分布式应用程序组件在网络中交互的架构风格。通常,编写REST API会选择Python(Flask、FastAPI)、JavaScript(Express.js)或Java。然而,C++却常常被忽视。这其实很可惜。



现代库,例如Crow、cpp-httplib和Drogon,可以让你在半小时内用C++创建高性能的REST API。得益于C++的运行速度和极低的内存消耗,这类API非常适合用于:



  • 对性能有高要求的微服务;
  • 嵌入式系统和IoT设备;
  • 处理大量并发请求;
  • 实现网关和代理服务器。


在本文中,我们将使用Crow库实践创建一个简单的REST API。你会发现,它并不比用Python复杂,而在运行速度上则快得多。



环境配置与安装Crow库



我们的项目将使用Crow——一个极简且非常快速的C++微Web框架。它支持路由、中间件、JSON序列化,并可在Windows、Linux和macOS上运行。



所需条件

  • C++17或更高版本的编译器(GCC 8+、Clang 7+、MSVC 2019+);
  • CMake 3.14或更高版本;
  • asio库(随Crow自动安装);
  • nlohmann/json库(用于处理JSON)。


安装Crow



Crow是一个header-only库。这意味着你不需要编译它——只需将头文件复制到项目中即可。最简单的方法是通过CMake FetchContent。



创建项目结构:

rest-api-cpp/├── CMakeLists.txt├── src/│   └── main.cpp└── include/


CMakeLists.txt文件内容:

cmake_minimum_required(VERSION 3.14)project(rest_api_cpp)

set(CMAKE_CXX_STANDARD 17)

# 引入Crowinclude(FetchContent)FetchContent_Declare( crow GIT_REPOSITORY https://github.com/ipkn/crow.git GIT_TAG master)FetchContent_MakeAvailable(crow)

# 引入nlohmann/jsonFetchContent_Declare( json GIT_REPOSITORY https://github.com/nlohmann/json.git GIT_TAG v3.11.2)FetchContent_MakeAvailable(json)

add_executable(rest_api src/main.cpp)target_link_libraries(rest_api PRIVATE Crow::Crow nlohmann_json::nlohmann_json)


之后执行:

mkdir build && cd buildcmake ..make


现在可以开始编写代码了。



使用Crow创建基础的REST API



我们来编写一个简单的任务管理API(Task Manager)。它将支持四种主要的HTTP方法:GET、POST、PUT、DELETE。



服务器框架与GET端点



#include <crow.h>#include <nlohmann/json.hpp>#include <vector>#include <string>

using json = nlohmann::json;

struct Task { int id; std::string title; bool completed;};

std::vector<Task> tasks = { {1, "学习Crow", false}, {2, "编写REST API", false}};int next_id = 3;

int main() { crow::SimpleApp app;

// GET /tasks — 获取所有任务 CROW_ROUTE(app, "/tasks") .methods("GET"_method) ([](){ json j = json::array(); for (const auto& t : tasks) { j.push_back({{"id", t.id}, {"title", t.title}, {"completed", t.completed}}); } return crow::response(j.dump()); });

app.port(8080).multithreaded().run();}


这段代码在8080端口启动了一个HTTP服务器。当向/tasks发送GET请求时,

博客

书籍推荐