Skip to content
Download

Routing Fundamentals

Routing determines which endpoint handles an incoming HTTP request.

In Mach, endpoints are mapped to an HTTP method and a route. When a request arrives, Mach uses both to find the endpoint that should handle it.

You can map an endpoint directly on your application:

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

This endpoint handles GET requests to /.

The first argument is the route, while the second is the endpoint handler that runs when the route is matched.

Mach provides mapping functions for the standard HTTP methods:

app.mapGet("/users", [] {
return mach::ok("Get users");
});
app.mapPost("/users", [] {
return mach::ok("Create user");
});
app.mapPut("/users", [] {
return mach::ok("Update user");
});
app.mapPatch("/users", [] {
return mach::ok("Partially update user");
});
app.mapDelete("/users", [] {
return mach::ok("Delete user");
});
app.mapHead("/users", [] {
return mach::ok();
});

Each mapping creates a separate endpoint.

Because the HTTP method is part of the route match, multiple endpoints can use the same path:

app.mapGet("/users", [] {
return mach::ok("Get users");
});
app.mapPost("/users", [] {
return mach::ok("Create user");
});

A GET /users request is handled by the first endpoint, while a POST /users request is handled by the second.

Routes can contain one or more static path segments:

app.mapGet("/users", [] {
return mach::ok("Users");
});
app.mapGet("/users/profile", [] {
return mach::ok("Profile");
});
app.mapGet("/health", [] {
return mach::ok("Healthy");
});

Each route represents a distinct path that Mach can match against an incoming request.

Routes don’t have to be entirely static. Mach also supports route patterns with parameters:

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

Here, {id} represents a value taken from the request path.

Route parameters and other pattern syntax are covered in detail in the next guide.

When a request reaches the application, Mach considers both its HTTP method and path when selecting an endpoint.

For example, given:

app.mapGet("/users", [] {
return mach::ok("Users");
});

the endpoint matches:

GET /users

but does not match:

POST /users
GET /products

If no endpoint matches the request, Mach returns a 404 Not Found response.

If the path matches an endpoint but the HTTP method does not, Mach returns a 405 Method Not Allowed response.


Next, you’ll learn how to define dynamic routes using route patterns.