These docs are for v0.12. Click to read the latest docs for v0.16.

Sometimes a custom Response object needs to be created instead of using something that is ResponseRepresentable. For instance, if you need to manually assign cookies.

Initialization

There are various convenience intializers for Response.

Empty

Empty responses are useful when the Status is the important content.

Response(status: .created)

Text

Text responses are created when you return a String in a route closure, but they can also be created manually.

Response(status: .enhanceYourCalm, text: "Too many requests")

JSON

JSON responses are created when you return Json() in a route closure, but they can also be created manually.

Response(status: .internalServerError, text: JSON([
    "message": "Uh oh"
]))

Redirect

Redirect the client to a different URL with a 301 status code.

Response(redirect: "http://google.com")

Cookies

To add cookies to the response, make sure it is mutable and set them on the cookies property.

app.get("cookie") { request in
    var response = Response(status: .ok, text: "Cookie set")
    response.cookies["id"] = "123"

    return response
}

Async

If you need to wait for a callback to complete before sending your response, you will want to use the async response initializer. It will give you a Stream object to which you can send Data and close when you are finished.

Response(async: { stream in
    try stream.send("hi".data, timingOut: 20)
		try stream.close()
})