Tomo.Log()


[Vapor3] Obtain GET/POST Request parameters

[09/12, 2018]

日本語 / English

This is Vapor3 tips on how to obtain GET/POST Request parameters for me.

Get Parameters

Obtain Get Parameter by name

Get the "search" parameter like this below.

URL: https://sample.com/page?serach=keyword

 if let word = req.query[String.self, at:"serach"] {
            print(word)   //keywrod 
 }

Decode objects that conform to the protocol "Content"

Create a struct/class that conforms to protocol "Content". Then, decode the struct/class to obtain parameters.

URL : https://sample.com/page?search=keyword
URL : https://sample.com/page?search=keyword&option=someoption

   struct GetParameter : Content {
            var search : String
            var option : String?
   }
        
   let parameters = try req.query.decode(GetParameter.self)

In this example, "search" is must parameter and option is an optional parameter. So if you access to "https://sample.com/page", Vapor3 throws errors.

Post Parameters

Decode objects that conform to the protocol "Content"

You can use the object that conforms to the "Content" protocol as same as "Get" parameter.
But there is a difference.

GET : req.query.decode
POST : req.content.decode

 struct PostParameter : Content {
      var search : String
      var option : String?
 }
        
 let parameters = try req.content.decode(PostParameter.self)