GraphQL in C++: cppgraphqlgen — A Powerful Tool for Modern APIs
GraphQL is a query language for APIs that allows clients to request only the data they need. Although GraphQL is most often associated with JavaScript (Apollo, Relay) or Python (Graphene, Strawberry), there is also an excellent solution for high-load systems in C++ — the cppgraphqlgen library. It provides a complete set of tools for building a GraphQL server-side in pure C++ with support for modern C++17/20 standards.
What is cppgraphqlgen?
cppgraphqlgen is a header-only library (with optional compilation into .so/.dll) that implements the GraphQL specification (June 2018). It generates type-safe code based on a schema (SDL — Schema Definition Language) and allows you to create efficient, multithreaded GraphQL servers.
Key features:
- Code generation from schema — you describe types, queries, and mutations in a
.graphqlfile, and thegraphqlgenutility creates C++ classes. - Type safety — all types are checked at compile time. No runtime type errors.
- Performance — minimal overhead, support for asynchronous resolvers (via
std::future). - Support for Subscriptions — via WebSocket or gRPC.
- Integration with any HTTP server — can be used with
crow,drogon,beast(Boost.Asio), or even a custom implementation.
Library Architecture
cppgraphqlgen consists of two parts:
- Code Generator (
graphqlgen) — reads the schema and creates header files with classes for each type, interfaces for resolvers, and helper functions. - Runtime Library — query parser, validator, executor, and response serializer.
Installation
The library is distributed via vcpkg or built from source:
git clone https://github.com/microsoft/cppgraphqlgen.gitcd cppgraphqlgenmkdir build && cd buildcmake .. -DCMAKE_BUILD_TYPE=Releasecmake --build . --target installUsing the generator requires node.js (it is written in TypeScript), but the runtime is pure C++.
Example: Creating a Simple GraphQL Server
First, create a schema schema.graphql:
type Query { hello: String user(id: Int!): User}
type User { id: Int name: String email: String}Then run the generator:
graphqlgen --schema schema.graphql --output ./generatedAfter this, files will appear in the generated folder: SchemaTypes.h, SchemaResolver.h, and others. Now write the resolvers:
#include "generated/SchemaTypes.h"#include "generated/SchemaResolver.h"
class QueryResolver : public graphql::schema::Query::Resolver {public: std::shared_ptr<graphql::schema::String> getHello() override { return std::make_shared<graphql::schema::String>("Hello, GraphQL from C++!"); }
std::shared_ptr<graphql::schema::User> getUser(int id) override { auto user = std::make_shared<graphql::schema::User>(); user->id = std::make_shared<graphql::schema::Int>(id); user->name = std::make_shared<graphql::schema::String>("John Doe"); user->email = std::make_shared<graphql::schema::String>("john@example.com"); return user; }};Now build the server using crow:
#include <crow.h>#include "generated/Schema.h"