REST
REST is a style of HTTP API: resources have URLs, methods mean GET/PUT/POST/DELETE, and representations are usually JSON. A C++ service implements that with a router plus a JSON library, not with a standard "REST" type.
Detailed Explanation
A resource is a noun (/orders/42). GET reads it and should not change it. PUT replaces it and is idempotent. DELETE removes it and is idempotent. POST creates or triggers a process and is not idempotent. Those promises are why a load balancer can retry a GET and must not blindly retry a POST.
C++ servers map a method and a path pattern to a handler. Crow: CROW_ROUTE(app, "/orders/<int>").methods("GET"_method)(...). Drogon uses attributes or METHOD_ADD. Beast makes you parse the target yourself. The handler reads path params, query string, and body, then writes a status and a body.
JSON is the usual representation (nlohmann::json, RapidJSON, simdjson). See the JSON page. Content-Type: application/json on requests and responses is part of the contract. Wrong type: 415 or a confused parser.
REST is not "I used HTTP". A single POST /api that takes an action field is an RPC. That can be fine; do not call it REST. REST is also not a requirement for a good API. gRPC is common in C++ backends that talk to other backends.
Versioning (/v1/orders), pagination, and error bodies ({"error":"..."} plus a 4xx) are conventions you document. Status codes carry the coarse outcome; the body carries the detail.
Idempotency keys on POST (a header the server stores) are how you retry a create without duplicating an order. C++ services implement that with a table of keys, not with a language feature.
Write handlers that take a request view and return a response value. Do not hold a mutex across a database call if you can avoid it; REST handlers are where thread-per-request servers run out of threads.
Code Examples
#include <nlohmann/json.hpp>
#include <string>
struct Order { int id; std::string status; };
nlohmann::json toJson(const Order& o) {
return {{"id", o.id}, {"status", o.status}};
}
// Handler sketch: GET /orders/42 -> 200 + JSON
std::string getOrder(int id) {
Order o{id, "SHIPPED"};
return toJson(o).dump();
}
int main() {
auto body = getOrder(42);
return body.find("SHIPPED") != std::string::npos ? 0 : 1;
}Common Gotchas
Retrying POST
the first request may have succeeded. Use an idempotency key or accept duplicates.
Returning 200 for every outcome
a missing order is `404`. A bad body is `400`. Clients and proxies key off the status.
Path vs query
`/orders/42` is a resource. `/orders?id=42` is a search. Be consistent.
JSON parse errors
do not crash the worker. Catch, return `400`, log.