Vapor fetching single values from the query string using subscripts

Hi guys,

in one of my Vapor routes I am using the following snippet:

let barcode = try req.content.get(String.self, at: "barcode")
        
if let code = try await Barcode.find(barcode, on: req.db) {
...
        }

which works fine, provided there is a key "barcode" in the content part of the request (otherwise I get a warning)

In fact I don't remember where I got that syntax from : req.content.get( ..., at: ) , to get a single value from JSON content of a request.

Looking at docs.vapor.codes/basics/content at Single Value I would think the right syntax should be:

let barcode: String? = req.query["barcode"]

But that gives always nil. Do I miss something? Is the first syntax still admitted? If so where is it described ?

Thanks for your help !

req.query fetches the query parameters which are part of the URL. So you might have something like

GET http://localhost:8080/foo?barcode=bar

here barcode is the query parameter.
req.content on the other hand decodes data from the request body:

POST /foo HTTP/1.1
content-type: application/json
content-length: 18

{"barcode": "bar"}

Ok @ptoffy, thanks ! Indeed, that's what is described in the docs.

Any idea where the other one (req.content.get(..,at: )) comes from ?

Are there other methods on req.content worth knowing?

You can have a look at the ContentContainer API docs

1 Like