C++ REST API Server: Routing, Middleware, JWT, Swagger [#50-2]
이 글의 핵심
Build a productive C++ REST layer: regex routes, global and per-route middleware, JSON with nlohmann/json, JWT hooks, and API docs workflow.
Introduction: “Express-like ergonomics in C++”
Goals:
- Verb + path routing (GET/POST/PUT/DELETE)
- Middleware chain (logging, CORS, auth)
- JSON request/response helpers
- Swagger/OpenAPI generation patterns (schema from code or annotations)
- Validation and consistent error JSON
Stack: C++17+, Boost.Beast, nlohmann/json (typical).
Scenarios
- Ultra-low latency microservices vs Node/Python.
- Embed HTTP in existing C++ engines or trading stacks.
- Resource-constrained edge nodes—small footprint vs full runtimes.
- Learning—implementing
router.get,use,nextclarifies web frameworks.
Common pitfalls:
- CORS: configure origins/methods/headers + OPTIONS.
- Empty JSON body: missing
Content-Type: application/jsonor reading body twice. - Auth bypass: middleware order—protect routes before handlers return 200 without checks.
Router design
Route: method,std::regexfor path, param names from:idsegments.match(method, path)returns handler + captured params.- Global middlewares run before route-specific ones.
Middleware chain
Execute middlewares in order; each calls next() to continue. Logging measures latency before/after handler.
Request / response
- Wrap Beast
request<string_body>; parse query fromtarget(), JSON body with nlohmann. - Response helpers:
status(),json(),set_header().
Auth middleware
- Read
Authorizationheader; Bearer JWT validation (library-specific); on failure return 401 without callingnext().
Swagger
- Maintain OpenAPI YAML/JSON alongside code, or generate from route metadata (method, path, body schema).
Related posts
- REST API client
- JSON parsing
- REST server patterns
Summary
Express-style routing + middleware maps cleanly onto Beast + nlohmann/json. Watch middleware order, CORS, and single read of request bodies for correct behavior.