GraphQL in C++: cppgraphqlgen Library for Creating APIs

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

GraphQL C++ Library: cppgraphqlgen



cppgraphqlgen is a modern C++ library for implementing the server-side of GraphQL. It allows developers to create type-safe, fast, and scalable APIs, leveraging the advantages of C++ static typing. The library generates code based on a GraphQL schema (.graphql files), which minimizes manual resolver writing and reduces the likelihood of errors.



Key Features

  • Code generation from schema — a schema.graphql file is provided as input, and C++ classes and functions are generated as output.
  • Type safety — all GraphQL types (String, Int, Float, Boolean, ID, Enum, Input, Object) are compiled into corresponding C++ types.
  • Support for Subscriptions — implemented via WebSocket and asynchronous streams.
  • Query validation — built-in syntax and semantic checking of GraphQL queries.
  • HTTP integration — works on top of any C++ HTTP server (e.g., beast from Boost).
  • Directive support — custom directives for extending functionality.


Installation

To install cppgraphqlgen, you need a compiler with C++17 support and the CMake build system. Installation via vcpkg or building from source:

# Via vcpkgvcpkg install cppgraphqlgen

# Build from repositorygit clone https://github.com/microsoft/cppgraphqlgen.gitcd cppgraphqlgenmkdir build && cd buildcmake .. -DCMAKE_BUILD_TYPE=Releasecmake --build . --target install


Usage Example

Let's look at a simple example: create a GraphQL schema for retrieving information about a user and a book. First, define the schema.graphql file:

type Query {  user(id: ID!): User  book(id: ID!): Book}

type User { id: ID! name: String! email: String}

type Book { id: ID! title: String! author: String!}


After code generation (using the graphqlgen command), we get the Generated.h file. Now let's write the resolvers in C++:

#include "Generated.h"#include <unordered_map>

// Example data (in a real project — a database)std::unordered_map<std::string, User> users = { {"1", {"1", "Alice", "alice@example.com"}}, {"2", {"2", "Bob", nullptr}}};

std::unordered_map<std::string, Book> books = { {"10", {"10", "C++ Primer", "Lippman"}}, {"20", {"20", "Effective Modern C++", "Meyers"}}};

// Resolver for Query.userUser resolveGetUser(const std::string& id) { auto it = users.find(id); if (it != users.end()) { return it->second; } throw std::runtime_error("User not found");}

// Resolver for Query.bookBook resolveGetBook(const std::string& id) { auto it = books.find(id); if (it != books.end()) { return it->second; } throw std::runtime_error("Book not found");}


Now set up the server and start processing requests:

#include <graphqlservice/GraphQLService.h>#include <beast/http.hpp>

int main() { // Create a service with the schema auto service = std::make_shared<graphql::service::GraphQLService>();

// Register resolvers service->addResolver("Query", "user", resolveGetUser); service->addResolver("Query", "book", resolveGetBook);

// Start the HTTP server (simplified) http::server server("0.0.0.0", 8080, service); server.run();

return 0;}


Error Handling and Validation

The library automatically checks the correctness of incoming requests. If a resolver throws an exception, cppgraphqlgen converts it into a GraphQL error with the appropriate code. Example of handling:


                
    
    

Recommendations