jsonhttpresponsevapor

Vapor - How do I return a JSON response with a specific Status Code?


Disclaimer: this question originally asked on the Vapor help channel on Slack

Easy question: if I'm sending a response like this

let response: ResponseRepresentable = try JSON(node: ["message": "User Created"])`

How can I set the status code for the response?


Solution

  • You can use the Response class directly, like this:

    let statusCode = Status.other(statusCode: 666, reasonPhrase: "damn it")
    let response = Response(status: statusCode, json: JSON(["error": "my error"]))
    

    See the Response Documentation for more info.