AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
AnCH REST library documentation

Introduction

AnCH REST library declares REST APIs independently of HTTP servers, and provides an HTTP client over native HTTP libraries (see anch-rest.todo for the work in progress).

Libraries

anch-rest is built by default (option ANCH_BUILD_REST , since 0.3). Optional libraries are skipped with a CMake status message when their dependencies are not found. Codecs (media types, JSON, Protocol Buffers, Thrift) are in anch-codec (see AnCH codec library documentation , since 0.3).

  • anch-rest-common : HTTP model (Method, Status, Headers, MediaType, Request, Response) and forms codecs (FormUrlEncoded, Multipart) ; it depends on anch-codec-json .
  • anch-rest-server : endpoints declaration and routing (Api).
  • anch-rest-client : HTTP client (Client) over a Transport.
  • anch-rest-curl : libcurl transport (CurlTransport), option ANCH_REST_CURL (built when libcurl is found).
  • anch-rest-nginx : nginx applications bridge (ANCH_REST_APPLICATION ), option ANCH_REST_NGINX , and nginx module sources (nginx/ , installed in share/anch/nginx-module ).
  • anch-rest-protobuf : Protocol Buffers RPC services (RpcService) served in an API with Connect and gRPC-Web protocols, Connect client ; option ANCH_REST_PROTOBUF (built with anch-codec-protobuf , when Protobuf is found).
  • anch-rest-grpc : gRPC server (GrpcServer) for the same RPC services ; option ANCH_REST_GRPC (built when gRPC is found).
  • anch-rest-thrift (header only): Thrift services in an API (installThrift) and Thrift transport over the client (ThriftTransport) ; option ANCH_REST_THRIFT (built with anch-codec-thrift , when Thrift and Boost headers are found).

Endpoints declaration

Endpoints are declared with a method and a path pattern. Endpoint function arguments are bound from the request: [const Request&], path parameters..., [Body<T>]. The result is serialized with the codec negotiated with Accept header:

api.get("/pets/{id}", [](uint64_t id) -> std::optional<Pet> { return findPet(id); }) // 404 when empty
.produces<anch::codec::Json>();
api.post("/pets", [](anch::rest::Body<Pet> pet) {
Pet saved = savePet(*pet);
return anch::rest::Response(anch::rest::Status::CREATED)
.header(anch::rest::header::LOCATION, "/pets/" + std::to_string(saved.id));
})
.consumes<anch::codec::Json>();
api.filter([](anch::rest::Request& request, const anch::rest::Next& next) {
return anch::rest::Response(anch::rest::Status::UNAUTHORIZED);
}
return next(request);
});
api.validate(); // every endpoint has its codecs
anch::rest::Response response = api.handle(request); // done by HTTP server adapter

Errors: invalid path parameter or body 400 , unknown path 404 , unknown method 405 (with Allow ), not acceptable 406 , unsupported media type 415 , HttpException status, other exceptions 500 . OPTIONS without endpoint is answered with 204 and Allow .

Media types without codec are read as a stream: a std::istream& last argument receives the raw body whatever its Content-Type is (absent included, empty stream without body). The client sends a stream with Call::body(input, contentType, size) or anch::rest::RawBody (streamed by the libcurl transport when the size is known):

api.put("/pets/{id}/image", [](const anch::rest::Request& request, uint64_t id, std::istream& image) {
saveImage(id, request.getHeaders().get(anch::rest::header::CONTENT_TYPE).value_or(""), image);
});
client.put("/pets/{id}/image", 42).body(std::make_unique<std::ifstream>("rex.png", std::ios::binary), "image/png", size).execute();

Forms

Form is an ordered list of Part (fields and files, a name can be repeated). FormUrlEncoded codec reads and writes application/x-www-form-urlencoded bodies and Multipart codec reads and writes multipart/form-data bodies (with files); fields are converted on server side like query parameters:

api.post("/login", [](anch::rest::Body<anch::rest::Form> form) {
std::string user = anch::rest::requiredFormField<std::string>(*form, "user"); // 400 when missing
std::optional<bool> remember = anch::rest::formField<bool>(*form, "remember"); // 400 when invalid
return login(user, remember.value_or(false));
})
.consumes<anch::rest::FormUrlEncoded>();
client.post("/login").body<anch::rest::FormUrlEncoded>(anch::rest::Form().add("user", "rex").add("password", pwd)).send();
api.post("/pets/{id}/photo", [](uint64_t id, anch::rest::Body<anch::rest::Form> form) {
const anch::rest::Part* photo = form->part("photo"); // file name, media type, content
return savePhoto(id, photo);
})
.consumes<anch::rest::Multipart>();
upload.add("description", "Rex").addFile("photo", "rex.png", anch::codec::MediaType("image", "png"), content);
client.post("/pets/{id}/photo", 42).body<anch::rest::Multipart>(upload).send();

Other types are read and written through a Form with their FormMapper (written by hand or generated by anch-oas): helpers convert fields ( addFormField , formField , formFields ), files ( addFormFile , requiredFormFile ), JSON parts ( addJsonFormField , jsonFormField ) and check anch-json constraints on server side ( checkFormConstraints ):

template<>
struct anch::rest::FormMapper<UploadPhoto> {
static void toForm(const UploadPhoto& value, anch::rest::Form& form, anch::codec::Side) {
anch::rest::addFormField(form, "description", value.description);
anch::rest::addFormFile(form, "photo", value.photo); // anch::rest::Part
}
static void fromForm(UploadPhoto& value, const anch::rest::Form& form, anch::codec::Side side) {
value.description = anch::rest::requiredFormField<std::string>(form, "description");
value.photo = anch::rest::requiredFormFile(form, "photo");
}
};
api.post("/pets/{id}/photo", [](uint64_t id, anch::rest::Body<UploadPhoto> upload) { return savePhoto(id, &upload->photo); })
.consumes<anch::rest::Multipart>();

Bodies are limited by side (FormLimits : body size, number of parts, part size, part headers size): over a limit, server answers 413 .

Large files do not need memory: multipart parts larger than FormLimits::maxMemoryPartSize (1 MiB) are read in temporary files (deleted with their last part copy), parts are written from their file and the client streams multipart bodies ( Content-Length is known, libcurl transport reads the stream):

limits.maxSize = limits.maxPartSize = 1024 * 1024 * 1024; // 1 GiB uploads, read in temporary files
limits.temporaryDirectory = "/var/tmp/uploads";
upload.add(anch::rest::Part::fromFile("video", "/data/video.mp4", anch::codec::MediaType("video", "mp4")));
client.post("/videos").body<anch::rest::Multipart>(upload).send(); // read from the file while it is sent

Part::open() reads a part in memory or in a file; Part::content() loads a file in memory.

CORS

Cross-Origin Resource Sharing is enabled on the API. Allowed methods are the methods of the routes matching the path. Preflight requests are answered before filters (they have no credentials) and CORS headers are added to every response, errors included:

api.cors({
.origins = {"https://app.example.com"}, // "*" for every origin
.headers = {"Content-Type", "Authorization"}, // "*" for every requested header
.exposedHeaders = {"Location"},
.credentials = true, // not allowed with "*" origin
.maxAge = std::chrono::hours(1)
});

A preflight with a not allowed origin, method or header is answered with 403 without CORS headers. Vary: Origin is added when origins are listed.

Client

Path placeholders are replaced in order and percent-encoded. Accepted codecs are part of the call type: as<T>() is checked at compile time and deserializes the response with the codec matching its Content-Type :

config.timeout = std::chrono::seconds(5);
anch::rest::Client client(std::make_unique<anch::rest::CurlTransport>(config), "https://api.example.com/v1");
client.filter(anch::rest::bearerAuth(token));
Pet pet = client.get("/pets/{id}", 42).accept<anch::codec::Json>().as<Pet>(); // HttpError when status >= 400
anch::rest::Response created = client.post("/pets").body<anch::codec::Json>(pet).send();
client.del("/pets/{id}", 42).execute();

Network errors (connection refused, timeout, TLS) are reported with TransportError.

Fields constraints

anch-json fields constraints ( anch::val::required , anch::val::minLength , ...) are checked by the Json codec according to the side which uses it ( Side ):

  • server: request bodies are checked (invalid body: 400 response, its body is the error message with the path of the invalid value, such as /name: Length 0 is lower than minLength 1), responses are not ;
  • client: request bodies are checked before being sent ( body<Json>(value) raises anch::json::MappingError , nothing is sent), server responses are trusted and read with tolerance (unknown fields are ignored, indented responses are accepted).

Each side has its own mapping options (server and client can run in the same process), which can be changed at application initialization:

anch::codec::Json::options(anch::codec::Side::SERVER).serialize_check_constraints = true; // also check responses
anch::codec::Json::options(anch::codec::Side::CLIENT).deserialize_ignore_unknown_field = false; // strict client

Other codecs can behave according to the side with serialize(value, out, side) and deserialize(value, input, side) functions.

Protocol Buffers and gRPC

protoc messages are read and written by anch-codec-protobuf Protobuf ( application/x-protobuf ) and ProtobufJson ( application/json , Protobuf JSON mapping) codecs:

api.post("/pets", [](anch::rest::Body<pets::Pet> pet) { return save(*pet); })
.consumes<anch::codec::Protobuf>().produces<anch::codec::Protobuf>();

RPC services are declared once and served with three protocols: Connect and gRPC-Web unary calls in an API (HTTP/1.1: nginx, curl, browsers) and gRPC (HTTP/2) with GrpcServer:

anch::rest::RpcService service("pets.PetStore");
service.unary<pets::GetPetRequest, pets::Pet>("GetPet", [](const pets::GetPetRequest& request, anch::rest::RpcContext&) {
if(request.id() != 1) {
throw anch::rest::RpcError(anch::rest::RpcCode::NOT_FOUND, "No pet"); // Connect, gRPC-Web and gRPC status
}
return findPet(request.id());
});
anch::rest::installRpc(api, service); // POST /pets.PetStore/GetPet (Connect, gRPC-Web): rest/rpcApi.hpp
anch::rest::GrpcServer server; // anch-rest-grpc
server.addService(service).listen("0.0.0.0:50051");
server.start();
// ...
server.shutdown();
pets::GetPetRequest request;
request.set_id(1);
pets::Pet pet = anch::rest::callRpc<pets::Pet>(client, "pets.PetStore", "GetPet", request); // Connect client: rest/rpcClient.hpp

Handler HttpException status is converted ( 400 is INVALID_ARGUMENT , 404 is NOT_FOUND , ...), other exceptions are INTERNAL without message. Request and response metadata (HTTP headers, gRPC metadata) are given by RpcContext. Native gRPC clients use grpc_cpp_plugin stubs. Only unary calls are supported.

Apache Thrift

Structures generated by thrift –gen cpp are read and written by anch-codec-thrift ThriftBinary ( application/vnd.apache.thrift.binary ), ThriftCompact ( .compact ) and ThriftJson ( .json ) codecs. Thrift services are served over HTTP by an API, as Thrift THttpServer (the protocol is chosen with the Content-Type , application/x-thrift is the binary protocol), and generated clients call them through an anch-rest client:

auto handler = std::make_shared<PetStoreHandler>(); // implements generated PetStoreIf
anch::rest::installThrift(api, "/thrift/pets", std::make_shared<pets::PetStoreProcessor>(handler)); // rest/thriftRpc.hpp
auto transport = std::make_shared<anch::rest::ThriftTransport>(client, "/thrift/pets"); // rest/thriftTransport.hpp
pets::Pet pet;
pets.getPet(pet, 1); // declared exceptions are raised by the generated client

nginx module

An application is a shared library which declares its API factory:

std::unique_ptr<anch::rest::Api>
createApi(std::string_view config) { // config: second anch_rest_app argument
auto api = std::make_unique<anch::rest::Api>();
api->get("/api/pets/{id}", findPet).produces<anch::codec::Json>(); // routes see the whole URI
return api;
}
ANCH_REST_APPLICATION(createApi)

The module is built with nginx (--with-threads to execute handlers in a thread pool):

./configure --with-threads --with-compat --add-dynamic-module=<anch-rest/nginx>
make modules
AnCH framework base namespace.
Definition app.hpp:30

nginx configuration:

load_module modules/ngx_http_anch_rest_module.so;
thread_pool default threads=16;
http {
server {
location /api/ {
anch_rest_app /usr/lib/libmyapi.so "/etc/myapi.conf";
anch_rest_thread_pool default; # default value; "off" executes handlers in the event loop
anch_rest_buffers 4 16k; # default value: response buffers of a request
}
}
}

Libraries are loaded when configuration is read (nginx -t reports loading errors) and APIs are created in each worker process.

Request and response bodies are streamed (anch::cutils::CIStream and anch::cutils::COStream on the module C functions):

  • in a thread pool, the handler is started as soon as request headers have been read. It reads the request body while nginx receives it (unbuffered body: at most client_body_buffer_size bytes are waiting for the handler), and its response body is sent while it is written, with at most anch_rest_buffers in memory: the handler waits while they are being sent ;
  • the response is started (status and headers) when more than one buffer has been written, with chunked transfer encoding, or at the end of the body with its Content-Length when it fits in one buffer. An error raised before the start is answered with 500 , an error raised after closes the connection (truncated response) ;
  • an application can stream a large response with Response::stream ; the request outlives the response body writer, which can read the request body ;
  • a slow client keeps a thread pool thread busy while it sends its request body, or receives the end of a response larger than buffers: thread pool size, client_body_timeout and send_timeout bound it ;
  • without thread pool (anch_rest_thread_pool off ), the handler is executed in the event loop: the request body is buffered by nginx (memory, then temporary file) and read in blocks, and the response body is given to nginx as it is written, without flow control (a large response stays in memory until it has been sent).