Devices example¶
examples/Devices returns a list of Device records and a single device by id, with the typical 200 / 400 / 404 trio of typed results.
Source¶
examples/Devices/src/main.cpp:
| examples/Devices/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 83 84 85 86 87 88 89 90 91 92 93 | |
examples/Devices/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;
};
What it shows¶
- Returning a
std::vector<T>from a handler. The framework serialises the entire vector as a JSON array — no special-casing required. - Organising the response DTO in a separate header (
Device.hpp) so the type can be reused. - The fluent route API on the
:idroute:.WithSummary(...)+.Handle(lambda). - Returning a
std::variant<JsonResult, BadRequestResult, NotFoundResult>to express the 200 / 400 / 404 outcomes. The framework picks the right status and serialises the body automatically. - Parsing path parameters from
HttpRequest::paramsand translating parse failures into a typedResults::BadRequest().
Try it¶
cmake -S . -B build
cmake --build build
./build/Devices
In another terminal:
curl http://localhost:8080/api/devices
curl http://localhost:8080/api/devices/1
curl -i http://localhost:8080/api/devices/abc # 400 Bad Request
curl -i http://localhost:8080/api/devices/999 # 404 Not Found
Next steps¶
- See Results for the typed result family.
- See Route options for adding summary, tags, and an OpenAPI operation id to this route.
- See the OpenAPI example for the end-to-end extension that generates a spec from this pattern.
- Browse all examples.