Optional parameter path component

Hi all,

I am trying to apply the tip given at docs.vapor.codes/basics/routing > Parameters

namely to handle the possibility of nil for a parameter path component.

However if my route is :

      wastes.get(":scan", use: self.returnWastes)

and the calling http request is:

  let API_URL: String = "http://127.0.0.1:80/"
    func getWastes() async -> [Waste] {
        let url = URL(string: API_URL + "wastes")!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        do {
            let (data, _) = try await URLSession.shared.data(for: request)
            return try JSONDecoder().decode([Waste].self, from: data)
        } catch {
            print("Could not read wastes : \(error)")
            return []
        }
    }

The server returns an error.

So how should I formulate the url so that a nil value is read by the server ?

Path parameters are typically mandatory because they identify a specific resource. Leaving it out like you do in your client code executes a request to a different endpoint: /wastes vs /wastes/:scan. You'll need to register both endpoints, the first one to return all resources independently of scan and the second to return one (or a group, related to the scan) in particular.

Otherwise you can also register one endpoint and add the scan ID as query parameter.

FYI we also have a Vapor Discord server at Vapor

Thanks @ptoffy I got it. I simply registered the two routes one with and the other without the parameter and that seems to work. Next time on Discord !