OpenAPI example¶
examples/OpenApiExample shows the BaldrOpenApiExtension end-to-end: route metadata (WithSummary, WithOperationId, WithTag) feeds an auto-generated OpenAPI 3.0.3 document, and the Scalar UI is mounted alongside it.
Source¶
examples/OpenApiExample/src/main.cpp:
| examples/OpenApiExample/src/main.cpp | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
examples/OpenApiExample/src/Device.hpp:
Device.hpp
#pragma once
#include <string>
struct Device
{
int id;
std::string uuid;
std::string mac;
std::string firmware;
std::string created_at;
std::string updated_at;
};
examples/OpenApiExample/src/User.hpp:
User.hpp
#pragma once
#include <string>
struct User
{
int id;
std::string name;
};
What it shows¶
- Wiring
BaldrOpenApiExtensionon the builder via.WithExtension<...>([](auto& ext){ ... })and configuringOpenApiOptions(title / version / description). - Using the fluent
RouteRegistrationAPI:.WithSummary,.WithTag,.Handle(...). - Grouping routes under a common prefix with
app->MapGroup("/api/v1", [](auto& group){ ... }). - Returning a
std::variantof typed results from theusers/:idhandler (JsonResult/BadRequestResult/NotFoundResult) — the OpenAPI extension reflects on the success branch and emits the response schema. - Mounting
baldr::MapScalarUi(*app)to expose the Scalar UI alongside the auto-generated spec.
Try it¶
cmake -S . -B build
cmake --build build
./build/OpenApiExample
In another terminal:
curl http://localhost:8080/openapi.json | jq '.paths, .components.schemas'
# Scalar UI is served at /scalar (open in a browser)
The document contains:
GET /api/v1/users— summaryFetch users, taggedusers, response schema$reftoUser.GET /api/v1/users/:id— summaryGet a user by id, taggedusers, response schema$reftoUser.components.schemas.User— derived from the C++ struct.
Next steps¶
- See OpenAPI extension for the full options reference, including path templating and JSON Schema dialect limitations.
- See Route options for the full list of metadata setters.
- Browse all examples.