Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Routing and Handlers

Build an HTTP application with ntex::web. The module provides routing, request extractors, and responses, along with middleware and testing tools.

Use web::App to assemble the application. You register routes and group them into resources and scopes. You can also add middleware, filters, and fallback services. ntex builds these into the service that handles requests.

The server evaluates your application factory independently in each worker:

use ntex::web::{self, HttpResponse};

#[ntex::main]
async fn main() -> std::io::Result<()> {
    web::server(async |_| {
        web::App::new()
            .route(
                "/",
                web::get().to(async || HttpResponse::Ok().body("Hello")),
            )
    })
    .bind("127.0.0.1:8080", ntex::SharedCfg::default())?
    .run()
    .await
}

The factory returns an application factory, not a running service. HttpService uses it to create an application service for each connection. Application services are never shared between workers.

A worker can invoke the outer factory again when its service needs to be recreated. Keep setup repeatable; do not rely on it running exactly once.

For workers, server configuration, and application state, see Server and Worker and request state.

A Small Notes API

Start with a read-only API for a notebook. It needs a list endpoint, a detail endpoint, and a health check. Keeping those routes together gives us a useful application to grow without hiding routing behind a database dependency:

use ntex::web::{self, HttpResponse};

mod notes {
    use ntex::web::{self, HttpResponse, types::{Json, Path}};
    use serde::Serialize;

    #[derive(Serialize)]
    struct Note {
        id: u32,
        title: &'static str,
    }

    fn saved_notes() -> Vec<Note> {
        vec![
            Note { id: 1, title: "Learn routing" },
            Note { id: 2, title: "Add application state" },
        ]
    }

    async fn list() -> Json<Vec<Note>> {
        Json(saved_notes())
    }

    async fn show(id: Path<u32>) -> Option<Json<Note>> {
        let id = id.into_inner();
        saved_notes().into_iter().find(|note| note.id == id).map(Json)
    }

    pub fn configure(cfg: &mut web::ServiceConfig) {
        cfg.service(web::resource("/notes").route(web::get().to(list)));
        cfg.service(
            web::resource("/notes/status")
                .route(web::get().to(async || "ready")),
        );
        cfg.service(
            web::resource("/notes/{id}").route(web::get().to(show)),
        );
    }

    pub async fn missing() -> HttpResponse {
        HttpResponse::NotFound().json(&serde_json::json!({
            "error": "unknown API path"
        }))
    }
}

#[ntex::main]
async fn main() -> std::io::Result<()> {
    web::server(async |_| {
        web::App::new()
            .service(
                web::scope("/api").service(
                    web::scope("/v1")
                        .configure(notes::configure)
                        .default_service(web::to(notes::missing)),
                ),
            )
            .default_service(web::to(async || {
                HttpResponse::NotFound()
                    .content_type("text/plain; charset=utf-8")
                    .body("Unknown path")
            }))
    })
    .bind("127.0.0.1:8080", ntex::SharedCfg::default())?
    .run()
    .await
}

This example uses serde with its derive feature and serde_json, alongside ntex with a runtime feature such as tokio. The notes are fixed data, not a persistent store. That keeps the first version easy to run; replacing saved_notes() with a database query comes after Application State.

The full path is the outer scope prefix, the inner scope prefix, and the resource path joined together:

RequestResult
GET /api/v1/notesA JSON array of notes
GET /api/v1/notes/1The first note as JSON
GET /api/v1/notes/99404, because the handler returns None
GET /api/v1/notes/statusPlain-text ready
GET /api/v1/missingThe versioned scope’s JSON 404
GET /elsewhereThe application’s plain-text 404

Register /notes/status before /notes/{id}. The router does not favor a literal path over a parameter automatically. If the parameter route comes first, it captures status; the Path<u32> extractor then fails instead of trying another resource. Matching a resource and extracting its arguments are separate steps.

There are also two different kinds of missing note here. An unknown path reaches a fallback service. A known detail path with an unknown ID reaches show, which returns None. The response happens to be 404 in both cases, but the scope fallback does not run for the second one. If every API error must have the same JSON shape, return an explicit JSON error response from show too; a routing fallback cannot rewrite handler responses.

The notes module owns its route handlers and exposes a registration function and a fallback. The application owns the public prefix and version, so the module does not bake /api/v1 into every path. You can later mount the same configuration below a different scope without rewriting its handlers.

Handlers

Use App::route() to connect a path and HTTP method to a handler:

use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new()
    .route("/users", web::get().to(async || HttpResponse::Ok()))
    .route(
        "/users",
        web::post().to(async || HttpResponse::Created()),
    );

A handler receives request extractors. Each extractor implements FromRequest. The handler returns a value that implements Responder. See Extractors and Responders for the built-in types and for writing your own. The basics example shows handlers that combine path and session extractors with several responders, and the extractors examples cover JSON, form, and multipart bodies.

Each call to App::route() creates a separate Resource containing one Route. The route’s method and custom guards become resource guards. You can therefore register the same path several times with different guards.

When several routes share a path, group them in a web::resource() and register it with App::service(). A resource can have its own name and fallback service. It can also have middleware and filters:

use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new().service(
    web::resource("/users/{id}")
        .name("user")
        .route(web::get().to(async || HttpResponse::Ok()))
        .route(web::delete().to(async || HttpResponse::NoContent())),
);

Resource::to() adds a route without a method guard, so it accepts every HTTP method:

use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new().service(
    web::resource("/health").to(async || HttpResponse::Ok()),
);

You can also use attribute macros for common routes. Pass the generated service directly to App::service():

use ntex::web::{self, HttpResponse};

#[web::get("/health")]
async fn health() -> HttpResponse {
    HttpResponse::Ok().into()
}

let app = web::App::<()>::new().service(health);

Method-specific route helpers include get, post, put, delete, patch, head, and query. For other methods, use web::method(), as in web::method(Method::OPTIONS).

Method matching is exact. A GET route does not also register HEAD, and ntex does not add an OPTIONS route for you. Register those methods explicitly when clients need them.

Choosing a Handler Return Type

Choose the smallest return type that expresses the endpoint’s contract. A String or &'static str produces a plain-text 200 OK, which suits a health check. Json<T> serializes a value implementing serde::Serialize and sets the JSON content type. The notes list uses this form because its successful result needs no special status or headers.

Return HttpResponse when the endpoint must choose a status, add headers, or build a body explicitly. For example, a future create endpoint can use HttpResponse::Created().json(&note), while a delete endpoint can return HttpResponse::NoContent().build().

Option<T> is convenient for a lookup: Some(value) uses the value’s responder, and None becomes 404 Not Found. Result<T, E> separates a successful responder from an error that implements WebResponseError for your application’s error domain. Neither wrapper changes how routes match. For extraction, custom response types, and error handling, continue with Extractors and Responders and Web Application Errors.

Choosing a Registration Style

Use App::route() for a small endpoint. Choose an explicit Resource when one path has several methods or needs a name. A resource also lets you attach middleware, filters, or a fallback to that path.

Use a Scope when several resources share a path prefix or policy. web::service() is a lower-level option for code that already implements an ntex service over WebRequest. Most handler-based applications do not need it.

Builder Order

Configure application-wide settings before registering services. The App builder has two phases:

  • In the settings phase, use middleware() and filter() to add layers. Set routing behavior with case_insensitive_routing(), attach configuration with with_config(), and register external URLs with external_resource().
  • The first call to route(), service(), configure(), or default_service() starts service registration. After that, only route(), service(), and default_service() are available.
use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new()
    // Application-wide settings
    .case_insensitive_routing()
    .external_resource("docs", "https://docs.example.com/{page}")
    // Service registration
    .route("/", web::get().to(async || HttpResponse::Ok()))
    .default_service(web::to(async || HttpResponse::NotFound()));

Calling a setting such as external_resource() after route() does not compile. The same ordering rule applies to Scope settings. Add guards with guard() before registering services. Add layers with middleware() and filter(), and set case_insensitive_routing() in that phase too.

How Routing Works

Routing chooses a resource by its path and guards, then chooses a route within that resource. Request-target settings control which form of the path reaches the router.

Request-target validation and normalization

You can validate request targets before they reach your application and normalize them before routing. Validation and normalization are both disabled by default for HTTP/1 and HTTP/2.

With these defaults, routing sees the original path structure. /a/../users does not automatically match /users. The router still decodes individual segments for matching and parameters, so /%75sers can match /users. The request URI keeps its original percent-encoding and query spelling.

Malformed targets can reach application code in this mode. HTTP message framing, mandatory HTTP/2 pseudo-header checks, UTF-8 and representation limits remain enforced. HTTP/1 also rejects raw non-ASCII bytes in the request target with 400 Bad Request; clients must percent-encode them.

HTTP/1 Host-header validation is separate and also disabled by default. Enable it with HttpServiceConfig::set_host_validation(true). Requests with more than one Host header and HTTP/1.1 requests without one are always rejected with 400 Bad Request.

Enable validation and normalization together in the HTTP service configuration passed to the listener. For example, pass this configuration to web::server(...).bind(...):

use ntex::{SharedCfg, http::HttpServiceConfig};

let config = SharedCfg::new("HTTP")
    .add(HttpServiceConfig::new().set_request_target_normalization(true));

With normalization enabled, ntex first validates target syntax and method-specific forms during HTTP/1 and HTTP/2 decoding. It then normalizes percent-encoding, dot segments, scheme, host and port. All application layers see the normalized target, including middleware, filters, guards, nested scopes, handlers and the application fallback.

If ntex cannot validate or normalize the target within the URL length limit, it returns 400 Bad Request. This happens before application middleware or filters run. The same setting applies to lower-level HttpService handlers without an App.

Normalization does not redirect clients or merge duplicate slashes. Application rewrites are not automatically validated or normalized again before routing. Test request builders bypass transport decoding and preserve raw targets.

For explicit processing, use the public urly::Url::validate_target() and urly::Url::normalize() APIs. Callers must also enforce method-specific forms.

Enable validation alone to reject malformed targets while keeping valid ones byte-for-byte. This is useful in proxies or when verifying signatures over the raw target:

use ntex::{SharedCfg, http::HttpServiceConfig};

let config = SharedCfg::new("HTTP")
    .add(HttpServiceConfig::new().set_request_target_validation(true));

Validation-only mode performs the same syntax and method-form checks. Failures return the same 400 Bad Request. A valid target such as /%41/../b reaches the application unchanged.

Normalization always validates first. The validation setting therefore has no effect while normalization is enabled.

Routing stages

A request moves through the application in several stages:

  1. Application middleware wraps the application service.
  2. Application filters process the incoming WebRequest.
  3. The application router finds a Resource whose path and resource guards match.
  4. Resource middleware wraps the selected resource’s filter and routes.
  5. The resource filter processes the request.
  6. The resource checks its routes in registration order. A route matches only if all its method and custom guards pass.
  7. The first matching route calls its handler.

Middleware can return a response without calling the service it wraps. When that happens, ntex skips every later stage.

Where routing stops determines which fallback runs:

  • If no resource path-and-guard combination matches, the application default service runs. The built-in application default returns 404 Not Found.
  • If a resource path matches but none of its routes match, the resource default service runs. The built-in resource default returns 405 Method Not Allowed.
  • Resource fallbacks are independent of application and scope fallbacks.
use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new()
    .service(
        web::resource("/reports")
            .route(web::get().to(async || HttpResponse::Ok()))
            .default_service(
                web::to(async || HttpResponse::MethodNotAllowed()),
            ),
    )
    .default_service(
        web::to(async || HttpResponse::NotFound().body("Unknown path")),
    );

Guards restrict which requests a resource or route accepts. Resource guards help the application router choose a resource. Route guards run after that choice. They can check methods, headers, or custom conditions:

use ntex::http::Method;
use ntex::web::{self, guard, HttpResponse};

let app = web::App::<()>::new().service(
    web::resource("/events").route(
        web::route()
            .method(Method::POST)
            .guard(guard::Header("content-type", "application/json"))
            .to(async || HttpResponse::Accepted()),
    ),
);

Guards receive only the request head, so they can check methods, headers, and other request metadata. They cannot inspect the body or values produced by extractors. Use a filter, extractor, or handler for those checks.

The guard’s location determines what happens when the method does not match:

  • App::route("/reports", web::get().to(handler)) uses the application fallback for a non-GET request. The method guard belongs to the generated resource. Scope::route() behaves the same way.
  • web::resource("/reports").route(web::get().to(handler)) first selects the resource by path. If its method guard fails, it uses the resource’s default 405 Method Not Allowed response.

Use guards for routing decisions, not as the only authentication check. A header guard answers “does this resource match?”; it does not produce an explanation or automatically return 401 Unauthorized. A failed guard can let the router choose another resource or a fallback. For the notes API, keep public and private resource selection separate from checking a user’s credentials. An authentication filter or middleware can reject a request with an intentional status; see Filters and Middleware.

You can combine conditions with guard::Any(first).or(second), guard::All(first).and(second), and guard::Not(condition). For a condition not covered by the built-ins, guard::fn_guard() accepts a closure over the request head. Keep that closure quick and synchronous: body parsing and asynchronous database checks belong later in the pipeline.

Order Matters

Put specific patterns before broad dynamic or remainder patterns. ntex checks resources and scopes in registration order. The first matching path whose guards pass wins. Routes inside a resource follow the same rule:

use ntex::web::{self, App};

let app = App::default()
    .service(web::resource("/files/status").to(async || "ready"))
    .service(web::resource("/files/{path}*").to(async || "file"));

If you reverse these registrations, the remainder resource handles /files/status. Add an unguarded route with Resource::to() after guarded routes for the same reason. Once it matches, later routes cannot be reached.

Use App::middleware() to wrap the whole application. Use App::filter() to transform every incoming WebRequest before routing. Resources and scopes offer the same methods when the behavior should apply to only part of the application. See Web Application Filters and Middleware for details.

Route Path Format

Use route patterns to match fixed paths or capture parts of a path. Patterns contain static and dynamic segments separated by /. ntex adds a leading / to resource and scope paths when needed. Include it yourself to make the full route easier to read.

Static Paths

A static pattern matches the same path:

/users
/users/profile

Trailing slashes matter: /users and /users/ are different paths. Query strings are not included in path matching.

Routing is case-sensitive by default. Use App::case_insensitive_routing() to make static path segments ASCII case-insensitive. This does not change how dynamic segments match. Scopes can enable the same behavior for their nested routes.

Dynamic Segments

Write a dynamic segment as {name}. It matches one non-empty path segment:

/users/{id}
/teams/{team}/users/{user}

You can combine variables with static text or use several variables in one segment:

/releases/v{major}.{minor}
/files/{name}.{extension}

Add a regular expression as {name:regex} to restrict what a variable accepts:

/users/{id:[0-9]+}
/releases/{version:v[0-9]+\.[0-9]+}

The regular expression must match the whole segment. Invalid route patterns and regular expressions panic while the application is built. Define routes as trusted application configuration; do not build them from user input.

Remainder Matches

Add * after a dynamic variable to capture the rest of the path, including / separators:

/files/{path}*

This matches both /files/readme.txt and /files/images/logo.svg. The path value is readme.txt in the first case and images/logo.svg in the second. The default expression is .*, so the captured value may be empty. Remainder matches cannot use a custom regular expression.

A remainder value keeps its percent-encoding. A request for /files/my%20file.txt captures my%20file.txt. Decode it yourself if the handler needs the decoded path. Validate the value before using it as a file system path.

Static tail patterns such as /files/* also work, but a named remainder is usually clearer and works naturally with typed path extraction.

Multiple Patterns

A resource or scope can use an array or vector to accept several patterns:

use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new()
    .service(
        web::resource(["/health", "/status"])
            .to(async || HttpResponse::Ok()),
    );

Every pattern points to the same service.

When a multi-pattern resource is named, URL generation uses its first pattern. Put the canonical path first and treat the remaining patterns as aliases.

Accessing Path Variables

Use the typed Path extractor to read variables captured by a route:

use ntex::web::{self, HttpResponse};

async fn user(path: web::types::Path<(u32,)>) -> HttpResponse {
    let user_id = path.0;
    HttpResponse::Ok().body(format!("user {user_id}"))
}

let app = web::App::<()>::new().route(
    "/users/{id:[0-9]+}",
    web::get().to(user),
);

Tuples deserialize variables in path order. To access variables by name, use a struct that derives serde::Deserialize:

use ntex::web::{self, HttpResponse};

#[derive(serde::Deserialize)]
struct UserPath {
    organization: String,
    user_id: u32,
}

async fn user(path: web::types::Path<UserPath>) -> HttpResponse {
    HttpResponse::Ok().body(format!(
        "organization: {}, user: {}",
        path.organization,
        path.user_id,
    ))
}

let app = web::App::<()>::new().route(
    "/organizations/{organization}/users/{user_id:[0-9]+}",
    web::get().to(user),
);

The struct fields must have the same names as the route variables. This example requires the derive feature from serde.

For a notebook URL such as /notebooks/{notebook}/notes/{id}, a single Path<(String, u32)> reads both captures. A struct with notebook: String and id: u32 makes the relationship clearer as the route grows. Do not split this into separate Path arguments expecting each to consume a capture: each extractor reads the request’s full set of path variables.

A pattern restriction and a Rust type check solve different problems. The pattern /notes/{id:[0-9]+} rejects letters during routing, but a long string of digits can still overflow u32 during extraction. With DefaultError, a failed Path extraction produces 404 Not Found, and the handler is not called. Use a domain check in the handler for valid numbers that have no meaning in your application, such as a notebook ID the user cannot access.

You can also read variables directly from HttpRequest::match_info():

use ntex::web::{self, HttpRequest};

async fn file(req: HttpRequest) -> String {
    req.match_info()
        .get("path")
        .unwrap_or_default()
        .to_owned()
}

let app = web::App::<()>::new().route(
    "/files/{path}*",
    web::get().to(file),
);

ntex splits the path into segments before percent-decoding normal dynamic variables. It stores those decoded values in the request’s match information. An encoded slash such as %2F can therefore appear inside a decoded variable. Escapes that are not valid UTF-8 remain percent-encoded. Remainder values stay as they appear in the request path.

Path values are untrusted input. A variable that looked like one URL segment can decode to ../ or contain /. Validate it before using it as a file name, database key, or other identifier with stricter rules.

Scopes

A Scope groups related services under a shared path prefix:

use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new().service(
    web::scope("/api")
        .service(
            web::resource("/users")
                .route(web::get().to(async || HttpResponse::Ok())),
        )
        .service(
            web::resource("/users/{id}")
                .route(web::get().to(async || HttpResponse::Ok())),
        ),
);

These resources match /api/users and /api/users/{id}. You can nest scopes and use variables in their prefixes. Nested handlers can access those variables:

use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new().service(
    web::scope("/organizations/{org}")
        .route(
            "/users/{user}",
            web::get().to(
                async |path: web::types::Path<(String, String)>| {
                    HttpResponse::Ok()
                        .body(format!("{}:{}", path.0, path.1))
                },
            ),
        ),
);

A scope prefix matches complete path segments. scope("/api") can contain routes below /api/; it never matches /apix. The scope alone does not provide a handler for the bare /api path. Inside it, an empty resource pattern ("") matches /api, while "/" matches /api/:

use ntex::web::{self, HttpResponse};

let app = web::App::<()>::new().service(
    web::scope("/api")
        .route("", web::get().to(async || HttpResponse::Ok().body("/api")))
        .route("/", web::get().to(async || HttpResponse::Ok().body("/api/"))),
);

A scope can have its own guards, middleware, and filters. It can also have its own case-sensitivity setting and fallback service.

Once a scope matches, unmatched paths inside it use the scope fallback. Without a custom scope fallback, ntex returns its built-in 404 Not Found. It does not use the application fallback.

Named and External Resources

Give a resource a name when handlers need to link to it without hard-coding its path:

use ntex::web::{self, HttpRequest, HttpResponse, error::UrlGenerationError};

async fn index(req: HttpRequest) -> Result<HttpResponse, UrlGenerationError> {
    let url = req.url_for("user", ["42"])?;
    Ok(HttpResponse::Ok().body(url.to_string()))
}

let app = web::App::<()>::new()
    .service(
        web::resource("/users/{id}")
            .name("user")
            .route(web::get().to(async || HttpResponse::Ok())),
    )
    .route("/", web::get().to(index));

Here, the index handler generates an absolute URL such as http://some-host-name/users/42.

HttpRequest::url_for() returns a ntex::url::Url. Values fill dynamic segments in pattern order. For a resource inside a scope, supply values for dynamic scope segments before values for the resource itself.

Use HttpRequest::url_for_static() when the pattern has no dynamic segments. Each value is percent-encoded as one literal segment. URL delimiters in a value cannot change the generated URL’s structure.

Keep resource names unique across the application, including across scopes. Names are application-wide lookup keys. With duplicate names, generated links depend on which definition is found.

Generation can fail if the name is unknown, too few values are supplied, or the completed URL is invalid. Return UrlGenerationError from your handler, as above, to avoid panicking on those errors.

For an application resource, the request’s ConnectionInfo supplies the scheme and host. The resource and its containing scopes supply the path. ConnectionInfo uses forwarding headers only when your configured ForwardedPolicy allows them; the default policy ignores them. If you enable trust for a front-end proxy, have that proxy replace or correctly append to client-supplied forwarding headers before exposing generated URLs to clients. Without trusted forwarding information, the request target, Host, and server configuration supply connection information.

Use App::external_resource() to name a URL outside the application. Register it before the first route or service. You can also register it inside App::configure() through ServiceConfig::external_resource():

use ntex::web::{self, HttpRequest, HttpResponse, error::UrlGenerationError};

async fn docs(req: HttpRequest) -> Result<HttpResponse, UrlGenerationError> {
    let url = req.url_for("documentation", ["page1.html"])?;
    Ok(HttpResponse::Ok().body(url.to_string()))
}

let app = web::App::<()>::new()
    .external_resource(
        "documentation",
        "https://docs.example.com/{page}",
    )
    .route("/docs", web::get().to(docs));

The docs handler generates https://docs.example.com/page1.html. The external pattern supplies its own scheme and host, so generation does not use the request’s connection information. External resources are URL templates only. They do not participate in request routing.

Modular Configuration

Split route registration into functions when one builder chain becomes hard to read. App::configure() passes a ServiceConfig to a function so it can register part of the application:

use ntex::web::{self, HttpResponse};

fn configure_api(cfg: &mut web::ServiceConfig) {
    cfg.route(
        "/health",
        web::get().to(async || HttpResponse::Ok()),
    );
    cfg.service(
        web::resource("/version")
            .to(async || HttpResponse::Ok().body("4")),
    );
}

let app = web::App::default()
    .configure(configure_api)
    .route("/", web::get().to(async || HttpResponse::Ok()));

ServiceConfig can register routes, services, and external resources. These items join the application at the point where you call configure(). The callback does not create another routing boundary.

Both applications and scopes support modular configuration.

In the notes application, notes::configure is mounted on the versioned scope rather than on App. That makes /api/v1 a real routing boundary with its own fallback, while the callback itself remains only a registration helper. A sibling accounts::configure could register another group inside that scope. Because calling configure() starts service registration, attach shared middleware and filters to the scope before calling it.

The callback’s type must match the application state. The default ServiceConfig means ServiceConfig<(), ()>. When you introduce a named state type, change it to ServiceConfig<ApplicationState>. If a module does not depend on a particular application state, give the callback a generic St: web::State and accept &mut web::ServiceConfig<St>. A callback behind a state-changing filter must also name the resulting request-state type as its second type argument. These types connect the module to its surrounding pipeline; they do not create or clone state.

Testing Routes

Test routes without opening a network socket. Use web::test to initialize an App, send requests to it, and inspect the responses:

use ntex::http::StatusCode;
use ntex::web::{self, HttpResponse};
use ntex::web::test::{TestRequest, call_service, init_service};

#[ntex::test]
async fn user_route() {
    let service = init_service(
        web::App::new().route(
            "/users/{id}",
            web::get().to(async || HttpResponse::Ok()),
        ),
    )
    .await;

    let request = TestRequest::get()
        .uri("/users/42")
        .to_request();
    let response = call_service(&service, request).await;

    assert_eq!(response.status(), StatusCode::OK);
}

Test method mismatches and trailing slashes as well as successful requests. Cover dynamic-variable constraints, scope boundaries, and fallback services. Each exercises a different part of route selection.

A Routing Regression Test

A small table-driven test can capture the routing contract before you add more handlers. Here, status must reach the static route, an unsupported method must use the resource’s 405, and the scope must keep its own 404:

use ntex::http::{Method, StatusCode};
use ntex::web::{self, test, types::Path};

#[ntex::test]
async fn notes_routing_contract() {
    let app = test::init_service(
        web::App::new().service(
            web::scope("/api/v1")
                .service(
                    web::resource("/notes/status")
                        .route(web::get().to(async || "ready")),
                )
                .service(
                    web::resource("/notes/{id}").route(web::get().to(
                        async |id: Path<u32>| format!("note {}", id.into_inner()),
                    )),
                ),
        ),
    )
    .await;

    for (method, path, expected) in [
        (Method::GET, "/api/v1/notes/status", StatusCode::OK),
        (Method::GET, "/api/v1/notes/12", StatusCode::OK),
        (Method::GET, "/api/v1/notes/not-a-number", StatusCode::NOT_FOUND),
        (Method::POST, "/api/v1/notes/12", StatusCode::METHOD_NOT_ALLOWED),
        (Method::GET, "/api/v1/missing", StatusCode::NOT_FOUND),
    ] {
        let request = test::TestRequest::with_uri(path)
            .method(method)
            .to_request();
        let response = test::call_service(&app, request).await;
        assert_eq!(response.status(), expected, "{path}");
    }
}

This test exercises the application service, not an actual HTTP connection. It deliberately includes an extraction failure as well as a routing failure: both return 404, but take different paths through the application. For requests with bodies and JSON assertions, see Testing.

Lower-Level HTTP Service

Use the lower-level server builder when you need connection-level services before HttpService. These services can inspect or transform the Io object. They can also map the state passed to the HTTP and application services.

For most applications, start a server with web::server(factory). It is equivalent to web::HttpServer::new(factory).

After you register routes and services, the application builder can become a service factory. This factory converts http::Request values into http::Response values. HttpService uses it to handle HTTP/1.1 and HTTP/2 connections.

Here is the same server built at the lower level:

use ntex::{http, server, web, SharedCfg};
use ntex::web::HttpResponse;

#[ntex::main]
async fn main() -> std::io::Result<()> {
    server::build()
        .bind("http", "127.0.0.1:8080", SharedCfg::new("S"), async |_| {
            http::HttpService::new(
                web::App::new()
                    .route("/", web::get().to(async || {
                        HttpResponse::Ok().body("Hello")
                    }))
                    .build(),
            )
        })?
        .run()
        .await
}

To give the web application its own state instead of the surrounding service pipeline’s state, see Web Application State.