REST API requests in C++

Introduction

A C++ HTTP request is a library job, and the usual library is libcurl: the same engine as the curl command. The language adds what sockets do not have: std::string instead of hand-made buffers, a destructor instead of a forgotten close, an exception instead of a check after every call, and https — the handshake and the encryption are the library work, not yours. What the handshake does is on HTTPS and certificates in plain words. Sockets are still covered by the C page on REST: there the request is assembled by hand and only http works.

The library and the build line

You need the headers and the developer library. On Alpine the package is curl-dev, on Debian and Ubuntu it is libcurl4-openssl-dev.

sudo apt install libcurl4-openssl-dev

curl-config prints the version:

curl-config --version

libcurl 8.23.0

One line builds the program; -lcurl brings the library in at the link step:

g++ -std=c++20 -Wall -Wextra rest.cpp -o rest -lcurl

The Client class

The owner of the curl handle is a std::unique_ptr with a custom deleter: the object cannot be copied, and curl_easy_cleanup runs in the destructor, also when a function leaves through an exception. A plain callback function writes the answer into a std::string, and the method and the body arrive as std::string_view and std::string. The file rest.cpp:

#include <curl/curl.h> #include <format> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <string_view> namespace { struct CurlDeleter { void operator()(CURL* handle) const { curl_easy_cleanup(handle); } }; struct SlistDeleter { void operator()(curl_slist* list) const { curl_slist_free_all(list); } }; struct Response { long status = 0; std::string body; }; size_t append(char* data, size_t size, size_t count, void* user) { static_cast<std::string*>(user)->append(data, size * count); return size * count; } class Client { public: Client() : handle_(curl_easy_init()) { if (!handle_) { throw std::runtime_error("curl_easy_init failed"); } } Response request(std::string_view method, const std::string& url, const std::string& body = {}, long timeout = 10) { Response response; const std::string verb(method); curl_slist* raw = curl_slist_append(nullptr, "Accept: application/json"); if (!body.empty()) { raw = curl_slist_append(raw, "Content-Type: application/json"); } const std::unique_ptr<curl_slist, SlistDeleter> headers(raw); CURL* handle = handle_.get(); curl_easy_setopt(handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, verb.c_str()); curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers.get()); curl_easy_setopt(handle, CURLOPT_TIMEOUT, timeout); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, append); curl_easy_setopt(handle, CURLOPT_WRITEDATA, &response.body); if (!body.empty()) { curl_easy_setopt(handle, CURLOPT_POSTFIELDS, body.c_str()); curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, static_cast<long>(body.size())); } const CURLcode code = curl_easy_perform(handle); if (code != CURLE_OK) { throw std::runtime_error(curl_easy_strerror(code)); } curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &response.status); return response; } private: std::unique_ptr<CURL, CurlDeleter> handle_; }; } // namespace int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << std::format("usage: {} METHOD URL [BODY] [TIMEOUT]\n", argv[0]); return 2; } if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) { std::cerr << "curl_global_init failed\n"; return 1; } const std::string body = (argc > 3) ? argv[3] : ""; const long timeout = (argc > 4) ? std::stol(argv[4]) : 10; try { Client client; const Response response = client.request(argv[1], argv[2], body, timeout); std::cout << std::format("status: {}\nbody: {}\n", response.status, response.body); } catch (const std::exception& error) { std::cerr << "error: " << error.what() << '\n'; curl_global_cleanup(); return 1; } curl_global_cleanup(); return 0; }

A test server

The requests are checked against your own server: it answers JSON to all four methods, returns 404 for paths that start with /missing and sleeps for three seconds on /slow, which is what the timeout needs. The file server.py:

import json import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class Handler(BaseHTTPRequestHandler): def answer(self, code, payload=""): body = payload.encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self): if self.path == "/slow": time.sleep(3) if self.path.startswith("/missing"): self.answer(404, json.dumps({"error": "not found", "path": self.path})) return self.answer(200, json.dumps({"path": self.path, "method": "GET"})) def do_POST(self): body = self.rfile.read(int(self.headers.get("Content-Length", 0))) self.answer(201, json.dumps({"created": json.loads(body or b"{}")}, sort_keys=True)) def do_PUT(self): body = self.rfile.read(int(self.headers.get("Content-Length", 0))) self.answer(200, json.dumps({"replaced": json.loads(body or b"{}")}, sort_keys=True)) def do_DELETE(self): self.answer(204) ThreadingHTTPServer(("127.0.0.1", 8002), Handler).serve_forever()

python3 server.py

GET

The method, the address and the body come from the command line, so one program checks all four methods:

./rest GET http://127.0.0.1:8002/status

status: 200 body: {"path": "/status", "method": "GET"}

The status is the long from CURLINFO_RESPONSE_CODE, not a string: the server may answer with an error, and the request is still a success, only the status differs.

./rest GET http://127.0.0.1:8002/missing/rule

status: 404 body: {"error": "not found", "path": "/missing/rule"}

An https:// address needs no code change: CURLOPT_URL takes any scheme the installed libcurl was built with. A HEAD request checks it without printing a whole page:

./rest HEAD https://example.com/

status: 200 body:

POST

The body goes into CURLOPT_POSTFIELDS and its length into CURLOPT_POSTFIELDSIZE (libcurl does not copy the body, so the std::string lives until request() returns). Headers are collected in a curl_slist, which the unique_ptr frees as well:

./rest POST http://127.0.0.1:8002/rules '{"name":"rule1"}'

status: 201 body: {"created": {"name": "rule1"}}

PUT

For a PUT only the first word of the request changes; the path with the identifier and the complete object body are passed the same way:

./rest PUT http://127.0.0.1:8002/rules/r_id '{"name":"rule2"}'

status: 200 body: {"replaced": {"name": "rule2"}}

DELETE

A DELETE has no body, and 204 means "done, and the answer has no body":

./rest DELETE http://127.0.0.1:8002/rules/r_id

status: 204 body:

Timeouts

CURLOPT_TIMEOUT is the limit in seconds for the whole request. The server sleeps three seconds on /slow, so the timeout goes to one:

./rest GET http://127.0.0.1:8002/slow "" 1

error: Timeout was reached

A transport error is not a status code but an exception: the program prints the text from curl_easy_strerror and exits with code 1. A 4xx or 5xx answer is the opposite — a successful request, to be read from status.

What the library still does

The class above is the minimum. Beyond it libcurl does what is expensive to write by hand: connection reuse on one handle, redirects (CURLOPT_FOLLOWLOCATION), compression, HTTP/2, certificate checks and pinning, proxies, uploads and downloads, and parallel requests through curl_multi. JSON is still not its job: the body arrives as a string and goes to a library such as nlohmann/json.

Every command and every answer on this page was produced with g++ 15.2.0 and libcurl 8.23.0 (OpenSSL 3.5.9) on Alpine Linux 3.24.3 (x86_64) in a Docker container. The image has no curl headers: the curl-dev package was unpacked under /tmp and the build used -I/tmp/curl/root/usr/include and -L/usr/lib -l:libcurl.so.4. A normal machine needs only the build line above.

Article author: Arthur Isaev