Popular blog tags

C++ 和 与 REST Web Api 服务器进行交互编程(C++ REST SDK cpprestsdk)

Published

C++ 开发 RESTful API 已经不像十年前几乎只有 CppRestSDK(Casablanca)一种选择。

目前主流方案可以分为完整 Web Framework、轻量 HTTP 库、现代异步网络库、企业级框架四类。

old

C++ REST SDK - cpprestsdk 已经基本停止维护(微软不再主推)

C++ REST SDK(代码名称“Casablanca”)

https://github.com/Microsoft/cpprestsdk

提供现代的跨平台异步 API,用于与 REST 服务进行交互。

对任何 HTTP 服务器执行 REST 调用,内置有对 JSON 文档分析和序列化的支持
支持 OAuth 1 和 2,包括本地重定向侦听器
使 Websocket 连接到远程服务
基于 PPL 的完全异步任务 API,包含内置线程池
支持 Windows 桌面 (7+)、Windows Server (2012+)、通用 Windows 平台、Linux、OSX、Android 和 iOS。

 

Microsoft Cpp Rest SDK源码编译与建立HTTP服务器例子

https://www.jianshu.com/p/1ecdab88b8bf

 

Sample code of cpprestsdk (casablanca), it's a sample example for beginner to get started with cpprestsdk with database(currently PostgreSQL) integration with basic structure, programmer can extend it.

https://github.com/Meenapintu/Restweb

cpp-httplib库

C++使用 cpp-httplib库发布一个web api服务器

使用 cpp-httplib 作为 HTTP 服务器库

 

nlohmann/json(超轻量)

 

HTTP:libcurl(工业标准)

 

examples

json body = {
    {"ak", "xxx"},
    {"cmd", "GetWorkState"}
};

std::string bodyStr = body.dump();

curl_easy_setopt(curl, CURLOPT_URL, "https://api.xxx.com");
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, bodyStr.c_str());

// header
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

 

其他可选库

C++ REST SDK(代码名称“Casablanca”)

https://docs.microsoft.com/zh-cn/cpp/cloud/cloud-and-web-programming-in-visual-cpp?view=vs-2019

https://github.com/hellmonky/note/blob/master/RPC%E8%B0%83%E7%94%A8%E8%BF%87%E7%A8%8B%E7%9B%B8%E5%85%B3%E8%AE%B0%E5%BD%95/C%2B%2B%E8%B0%83%E7%94%A8RESTFull%20API%E5%AE%9E%E7%8E%B0%E5%8A%9F%E8%83%BD.md

 

2026

Drogon - 完整 Web Framework

Drogon is a modern C++ web application framework for building HTTP services, REST APIs, WebSocket applications, and full web backends

适合项目 企业后台

Crow - 轻量 HTTP 库

Crow is a lightweight C++ framework for building HTTP servers, REST APIs, and WebSocket applications. 

适合项目 小型 API、本地服务

Oat++ - 完整 Web Framework

Oat++ is an open-source C++ framework for building web services, REST APIs, microservices, and networked applications.

适合项目 企业 REST API、微服务、云原生