
# C++

Start with the [gRPC guide](../grpc.md) to get a Platform API token and download `platform.proto`. Install `protoc`, the `grpc_cpp_plugin`, and the gRPC and protobuf C++ libraries. See the [official C++ setup guide](https://grpc.io/docs/languages/cpp/quickstart/) for installation.

Generate the protobuf messages and service stub in the directory containing `platform.proto`:

```bash
protoc -I. --cpp_out=. platform.proto
```

```bash
protoc -I. --grpc_out=. \
  --plugin=protoc-gen-grpc="$(command -v grpc_cpp_plugin)" platform.proto
```

Save as `main.cc`:

```cpp
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>
#include "platform.grpc.pb.h"

int main() {
  const char* token = std::getenv("CR_RECONSTRUCT_API_TOKEN");
  if (!token || !*token) {
    std::cerr << "Set CR_RECONSTRUCT_API_TOKEN\n";
    return 1;
  }

  auto channel = grpc::CreateChannel(
      "reconstruct.dev:443", grpc::SslCredentials(grpc::SslCredentialsOptions{}));
  auto client = reconstruct::platform::v1::PlatformService::NewStub(channel);
  reconstruct::platform::v1::ListCatalogsRequest list_request;
  list_request.set_page_size(10);
  reconstruct::platform::v1::ListCatalogsResponse page;
  grpc::ClientContext list_context;
  list_context.AddMetadata("authorization", std::string("Bearer ") + token);

  auto status = client->ListCatalogs(&list_context, list_request, &page);
  if (!status.ok()) {
    std::cerr << status.error_message() << '\n';
    return 1;
  }

  for (const auto& catalog : page.catalogs()) {
    reconstruct::platform::v1::GetCatalogRequest get_request;
    get_request.set_catalog_id(catalog.catalog_id());
    reconstruct::platform::v1::GetCatalogResponse detail;
    grpc::ClientContext get_context;
    get_context.AddMetadata("authorization", std::string("Bearer ") + token);
    status = client->GetCatalog(&get_context, get_request, &detail);
    if (!status.ok()) {
      std::cerr << status.error_message() << '\n';
      return 1;
    }
    std::cout << detail.catalog_id() << ": " << detail.description() << '\n';
  }
}
```

Use this `CMakeLists.txt` to compile the generated files and client:

```cmake
cmake_minimum_required(VERSION 3.16)
project(reconstruct_client LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)

find_package(Protobuf CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)

add_executable(reconstruct_client
  main.cc platform.pb.cc platform.grpc.pb.cc)
target_link_libraries(reconstruct_client PRIVATE
  gRPC::grpc++ protobuf::libprotobuf)
```

Run `cmake -S . -B build`, then `cmake --build build` and `./build/reconstruct_client`.
