如何在30分钟内用C++编写REST API:初学者指南

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

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

开始课程

引言:为什么用C++做REST API并不可怕



许多初学者开发者认为C++对于创建Web服务来说过于复杂。然而,现代C++(从C++11标准开始)为开发高性能REST API提供了强大而优雅的工具。在本教程中,我们将在30分钟内使用轻量级库Crow创建一个完整的C++ REST API。



我们将学习如何配置服务器、处理GET和POST请求、使用JSON以及返回数据。文章结束时,您将拥有一个可运行的原型,可以作为自己项目的基础。



什么是REST API?



REST(Representational State Transfer)是一种用于创建Web服务的架构风格。REST API使用HTTP方法(GET、POST、PUT、DELETE)来管理资源。数据通常以JSON格式传输。



1. 环境准备:安装库



为了快速上手,我们将使用Crow库——一个极简的C++ Web框架,无需复杂配置。我们还需要一个用于处理JSON的库——nlohmann/json。



安装依赖(Linux/macOS)



# 安装必要的包sudo apt-get install libboost-all-dev cmake g++

# 下载Crow(单头文件版本)wget https://raw.githubusercontent.com/CrowCpp/Crow/master/include/crow.h

# 下载JSON库wget https://github.com/nlohmann/json/releases/download/v3.11.2/json.hpp


安装依赖(Windows + MinGW)



对于Windows,使用vcpkg:



vcpkg install crowvcpkg install nlohmann-json


2. 创建一个简单的C++ HTTP服务器



我们从基础服务器开始,它将响应请求。创建文件main.cpp:



#include "crow.h"

int main() { crow::SimpleApp app;

// 简单的GET路由 CROW_ROUTE(app, "/")([](){ return "你好,世界!C++ REST API正在运行!"; });

// 在8080端口启动服务器 app.port(8080).multithreaded().run();}


编译并运行:



g++ -std=c++17 -pthread main.cpp -o api_server./api_server


打开浏览器并访问http://localhost:8080。您将看到欢迎消息。



3. 添加JSON处理和CRUD操作



现在添加JSON支持,并实现一个内存中的简单数据库来存储用户。



启用JSON支持



#include "crow.h"#include "json.hpp"#include <vector>#include <string>

using json = nlohmann::json;

struct User { int id; std::string name; std::string email;};

std::vector<User> users;int next_id = 1;


GET路由:获取用户列表



CROW_ROUTE(app, "/users")([](){    json response = json::array();    for (const auto& user : users) {        response.push_back({            {"id", user.id},            {"name", user.name},            {"email", user.email}        });    }    return crow::response(response.dump());});


POST路由:创建新用户



CROW_ROUTE(app, "/users").methods("POST"_method)([](const crow::request& req){    auto body = json::parse(req.body);

User new_user; new_user.id = next_id++; new_user.name = body["name"]; new_user.email = body["email"];

users.push_back(new_user);

json response = { {"id", new_user.id}, {"name", new_user.name}, {"email", new_user.email} };

return crow::response(201, response.dump());});


DELETE路由:删除用户





                
                

博客

书籍推荐