Basics

In Vapor the default Router is the EngineRouter. You can implement custom routers by implementing one conformant to the Router protocol.

  1. let router = try EngineRouter.default()

There are two APIs available, one is supplied by the Routing library and a set of helpers is available in Vapor itself.

Registering a route using Routing

The on function on a AsyncRouter registers a route to the provided path. The following registers a GET /hello/world route.

It responds with "Hello world!" using futures.

  1. router.on(.get, to: "hello", "world") { request in
  2. return try Response(body: "Hello world!")
  3. }

The .get represents the HTTP method you want to use. to: "hello", "world" registers the path /hello/world.

For variable path components you can use parameters.

The trailing closure receives a request. The route can throw errors and needs to return a future response conforming type.

Registering a route using Vapor

In Vapor we add support for routes using the .get, .put, .post, .patch and .delete shorthands.

For variable path components you can use parameters here, too.

Vapor has an added benefit here in that you can return the Response itself in addition to Future<ResponseRepresentable> or Future<Response>.

  1. router.get("components", "in", "path") { request in
  2. return Response(status: .ok)
  3. }

After registering your routes

After registering routes to the Router, you must add the router to your services.

  1. services.register(router, as: Router.self)

Learn more about services in Getting Started → Services