-
Notifications
You must be signed in to change notification settings - Fork 0
Parsing Requests
Below are examples showing the different ways that data can be parsed in Kitura.
You can specify matching to a URL parameter by starting the path name with a ":". The name afterwards is the key to the parameter dictionary
router.get("/name/:name") { request, response, _ in
let name = request.parameters["name"] ?? ""
try response.send("Hello \(name)").end()
}
This will match to /name/Bob
, /name/Joe
but not /name
You can access query parameters through the queryParameters
dictionary in RouterRequest
router.get("/name") { request, response, _ in
let name = request.queryParameters["name"] ?? ""
try response.send("Hello \(name)").end()
}
In this example, if the incoming URL /name?name=Dan
, then the output will be "Hello Dan".
For post requests, the post body can be read as a string with the readString
method.
router.post("/name") { request, response, _ in
let name = try request.readString() ?? ""
try response.send("Hello \(name)").end()
}
The built in body parsing middleware can parse a variety of body types including JSON.
-
Import SwiftyJSON by adding it to your
Package.swift
file and by addingimport SwiftyJSON
to the top of your file. -
Specify that the body parser should be run on all paths starting with
/name
router.all("/name", middleware: BodyParser())
- Specify your path, retrieving the parsed body from the body property.
router.post("/name") { request, response, next in
guard let parsedBody = request.body else {
next()
return
}
switch(parsedBody) {
case .json(let jsonBody):
let name = jsonBody["name"].string ?? ""
try response.send("Hello \(name)").end()
default:
break
}
next()
}