Skip to content
Download

Results

Minimal API handlers return a reply that Mach uses to produce the HTTP response.

Mach represents replies using mach::Reply<T>, where T is the type of the response body.

A minimal handler can return a result directly:

app.mapGet("/hello", [] {
return mach::ok("Hello, World!");
});

mach::ok() creates a 200 OK reply containing the provided body.

Handlers that do not return a response body can use a bodyless reply:

app.mapDelete("/users/{id:int}", [] {
return mach::noContent();
});

The type carried by a reply matches the response body.

For example:

app.mapGet("/users/{id:int}", [](mach::Context& context) {
const int id = context.request.routeParam<int>("id");
return mach::ok(id);
});

Here, mach::ok(id) produces a reply containing an int.

User-defined types can also be returned:

struct User {
int id;
std::string name;
};
MACH_DEFINE_JSON(User, id, name)
app.mapGet("/users/{id:int}", [](mach::Context& context) {
const int id = context.request.routeParam<int>("id");
return mach::ok(User{
.id = id,
.name = "Alice"
});
});

Mach serializes the value when producing the response.

Mach provides helpers for common HTTP outcomes.

For example:

return mach::ok("Success");
return mach::noContent();
return mach::notFound();
return mach::unauthorized();

These helpers make the intended outcome of an endpoint explicit without manually setting the status code.

For the complete set of result helpers and overloads, see the API Reference.

Returned results define the main outcome of the endpoint, while context.response can be used to add extra response data.

For example:

app.mapGet("/users/{id:int}", [](mach::Context& context) {
const int id = context.request.routeParam<int>("id");
context.response.setHeader("X-Source", "users");
return mach::ok(id);
});

Here, the returned result provides the status and body, while the response API adds a header.

A handler must return a compatible reply type across all of its return paths.

For example, this works because both branches return bodyless replies:

app.mapDelete("/users/{id:int}", [](mach::Context& context) {
const int id = context.request.routeParam<int>("id");
if (id <= 0) {
return mach::notFound();
}
return mach::noContent();
});

When a handler returns a body, the reply type must remain compatible across its return paths.


You’ve now covered the core Minimal API workflow: defining endpoints, reading requests, binding bodies, modifying responses, and returning results.