Skip to content

Conversation

swhitty
Copy link
Owner

@swhitty swhitty commented Sep 4, 2025

Supports route parameters in @HTTPRoute handlers.

@HTTPRoute("/account/:id")
func accountID(_ req: HTTPRequest) async -> HTTPResponse {
   let id = req.routeParameters["id"] ?? ""
   return HTTPResponse(statusCode: .ok, body: id.data(using: .utf8)!)
}

A recent change to FlyingFox (swhitty/FlyingFox#171) makes route parameters available to other handlers.

Fixes: #3

🔮 Future Directions

I intend on making route parameters available to @JSONRoute in the future, but the plan is to explicitly type the params making this syntax possible;

@JSONRoute("/account/:id")
func accountID(_ id: Int) async -> Account {
   let account = try await repo.getAccount(id: id)
   return account
}

:id name will be linked to the id: Int

@swhitty swhitty merged commit e7e4a4b into main Sep 4, 2025
8 checks passed
@swhitty swhitty deleted the http-route-parameters branch September 4, 2025 12:17
@lhoward
Copy link

lhoward commented Sep 4, 2025

Would also be great if arguments can be arbitrary types that can be initialised by strings (e.g. ExpressibleByStringLiteral). That would eliminate a lot of boilerplate.

@swhitty
Copy link
Owner Author

swhitty commented Sep 4, 2025

Yep any type that conforms to HTTPRouteParameterValue can be a route parameter.

This currently works for closure routes which match parameters based on index (name == 0, beast == 1)

enum Beast: String, HTTPRouteParameterValue {
  case fish
  case dog
}

handler.appendRoute("GET /creature/:name?type=:beast") { (name: String, beast: Beast) -> HTTPResponse in
  return HTTPResponse(statusCode: .ok)
}

But my plan is that macros should be able to match on the argument name (where order is not important)

@HTTPRoute("GET /creature/:name?type=:beast")
func creature(type: Beast, name: String) -> HTTPResposne {

}

@lhoward
Copy link

lhoward commented Sep 4, 2025

Yes, this would be super useful. I have some rather unpleasant code to extract the parameters from the path in my JSON handlers (but still, only took two days to add REST support to OpenSRP so I'm not complaining).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

retrieving route parameters from @JSONRoute

2 participants