GraphQL API 在 C++ 上的实现:完整指南与示例

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

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

开始课程

使用C++构建GraphQL API:逐步教程



GraphQL是一种强大的API查询语言,允许客户端精确请求所需数据,不多不少。虽然C++并非构建Web API最流行的语言,但其性能和内存控制使其成为高负载系统的绝佳选择。在本教程中,我们将使用graphql-cpp库创建一个可运行的C++ GraphQL服务器。



准备工作



完成本项目需要:

  • 支持C++17的编译器(GCC 8+、Clang 7+、MSVC 2019+)
  • CMake 3.14或更高版本
  • graphql-cpp库(通过vcpkg安装或从源码构建)
  • 用于HTTP服务器的libmicrohttpd库


通过vcpkg安装依赖:

git clone https://github.com/microsoft/vcpkg.gitcd vcpkg./bootstrap-vcpkg.sh./vcpkg install graphql-cpp libmicrohttpd


创建基础项目结构



首先设置CMake项目。创建一个CMakeLists.txt文件:

cmake_minimum_required(VERSION 3.14)project(graphql-cpp-tutorial)

set(CMAKE_CXX_STANDARD 17)set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(graphql-cpp CONFIG REQUIRED)find_package(MHD CONFIG REQUIRED)

add_executable(graphql-server main.cpp)target_link_libraries(graphql-server graphql-cpp::graphql-cpp MHD::MHD)


现在创建包含最小服务器的主文件main.cpp:

#include <graphql-cpp/GraphQL.h>#include <microhttpd.h>#include <iostream>#include <string>

using namespace graphql::cpp;

// HTTP请求处理函数static enum MHD_Result request_handler(void* cls, struct MHD_Connection* connection, const char* url, const char* method, const char* version, const char* upload_data, size_t* upload_data_size, void** con_cls) { const char* response_str = "{\\"data\\":{\\"hello\\":\\"world\\"}}"; struct MHD_Response* response = MHD_create_response_from_buffer( strlen(response_str), (void*)response_str, MHD_RESPMEM_PERSISTENT ); MHD_add_response_header(response, "Content-Type", "application/json"); int ret = MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); return ret == MHD_YES ? MHD_YES : MHD_NO;}

int main() { struct MHD_Daemon* daemon = MHD_start_daemon( MHD_USE_INTERNAL_POLLING_THREAD, 4000, NULL, NULL, &request_handler, NULL, MHD_OPTION_END ); if (daemon == NULL) { std::cerr << "无法启动服务器" << std::endl; return 1; } std::cout << "服务器运行在 http://localhost:4000/graphql" << std::endl; getchar(); MHD_stop_daemon(daemon); return 0;}


定义GraphQL模式



现在添加一个真实的GraphQL模式。我们将创建一个Book类型和一个根Query类型:

#include <graphql-cpp/Schema.h>#include <graphql-cpp/Type.h>#include <vector>#include <memory>

using namespace graphql::cpp;

// 数据模型struct Book { int id; std::string title; std::string author; int year;};

// 图书仓库(模拟数据库)class BookRepository {public: static std::vector<Book> getAll() { return { {1, "战争与和平", "列夫·托尔斯泰", 1869}, {2, "罪与罚", "费奥多尔·陀思妥耶夫斯基", 1866}, {3, "大师与玛格丽特", "米哈伊尔·布尔加科夫", 1967} }; } static Book getById(int id) { auto books = getAll(); for (const auto& book

博客

书籍推荐