Files
cpp-httplib/docs-src/pages/ja/cookbook/s02-json-api.md
2026-04-10 18:47:42 -04:00

2.4 KiB

title, order, status
title order status
S02. JSONリクエストを受け取りJSONレスポンスを返す 21 draft

cpp-httplibにはJSONパーサーが含まれていません。サーバー側でもnlohmann/jsonなどを組み合わせて使います。ここではnlohmann/jsonを例に説明します。

JSONを受け取って返す

#include <httplib.h>
#include <nlohmann/json.hpp>

int main() {
  httplib::Server svr;

  svr.Post("/api/users", [](const httplib::Request &req, httplib::Response &res) {
    try {
      auto in = nlohmann::json::parse(req.body);

      nlohmann::json out = {
        {"id", 42},
        {"name", in["name"]},
        {"created_at", "2026-04-10T12:00:00Z"},
      };

      res.status = 201;
      res.set_content(out.dump(), "application/json");
    } catch (const std::exception &e) {
      res.status = 400;
      res.set_content("{\"error\":\"invalid json\"}", "application/json");
    }
  });

  svr.listen("0.0.0.0", 8080);
}

req.bodyはそのままstd::stringなので、JSONライブラリに渡してパースします。レスポンスはdump()で文字列にして、Content-Typeにapplication/jsonを指定して返します。

Content-Typeをチェックする

svr.Post("/api/users", [](const httplib::Request &req, httplib::Response &res) {
  auto content_type = req.get_header_value("Content-Type");
  if (content_type.find("application/json") == std::string::npos) {
    res.status = 415; // Unsupported Media Type
    return;
  }
  // ...
});

厳密にJSONだけを受け付けたいときは、Content-Typeを確認してから処理しましょう。

JSONを返すヘルパーを作る

同じパターンを何度も書くなら、小さなヘルパーを用意すると楽です。

auto send_json = [](httplib::Response &res, int status, const nlohmann::json &j) {
  res.status = status;
  res.set_content(j.dump(), "application/json");
};

svr.Get("/api/health", [&](const auto &req, auto &res) {
  send_json(res, 200, {{"status", "ok"}});
});

Note: 大きなJSONボディを受け取ると、req.bodyがまるごとメモリに載ります。巨大なペイロードを扱うときはS07. マルチパートデータをストリーミングで受け取るのように、ストリーミング受信も検討しましょう。

クライアント側の書き方はC02. JSONを送受信するを参照してください。