Dynamic routing

So far, we looked at routes that were static and did not change, but modern applications can have dynamic or user-generated content and need to handle URL paths that change. We can handle those using parameters that we can specify in our routes. Let's see how we can create these routes. To do so, we need to follow these steps:

  1. In our main.swift file, add the following new handler, which will get called with a request object that will contain a parameter:
drop.get("hello", String.parameter) { (_ req: Request) throws -> ResponseRepresentable in let name = try req.parameters.next(String.self) return "Hello \(name)"}
  1. Build and run the application again using the swift run command and go to http://localhost:8080/hello/John

Get Hands-On Full-Stack Development with Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.