C++ REST API Server: Routing, Middleware, JWT, Swagger [#50-2]

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, next clarifies web frameworks.

Common pitfalls:

  • CORS: configure origins/methods/headers + OPTIONS.
  • Empty JSON body: missing Content-Type: application/json or reading body twice.
  • Auth bypass: middleware order—protect routes before handlers return 200 without checks.

Router design

  • Route: method, std::regex for path, param names from :id segments.
  • 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 from target(), JSON body with nlohmann.
  • Response helpers: status(), json(), set_header().

Auth middleware

  • Read Authorization header; Bearer JWT validation (library-specific); on failure return 401 without calling next().

Swagger

  • Maintain OpenAPI YAML/JSON alongside code, or generate from route metadata (method, path, body schema).

  • 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.