Vapor Documentation Beta

Protocol Content

public protocol Content: Codable, RequestDecodable, ResponseEncodable

Convertible to / from content in an HTTP message.

Conformance to this protocol consists of:

  • Codable

  • RequestDecodable

  • ResponseEncodable

If adding conformance in an extension, you must ensure the type already conforms to Codable.

struct Hello: Content {
    let message = "Hello!"
}

router.get("greeting") { req in
    return Hello() // {"message":"Hello!"}
}
%3 Content Content Codable Codable Content->Codable ResponseEncodable ResponseEncodable Content->ResponseEncodable RequestDecodable RequestDecodable Content->RequestDecodable

Conforms To

ResponseEncodable

Can convert self to a Response.

RequestDecodable
Codable

Requirements

default​Content​Type

var defaultContentType: HTTPMediaType

The default MediaType to use when encoding content. This can always be overridden at the encode call.

Default implementation is MediaType.json for all types.

struct Hello: Content {
    static let defaultContentType = .urlEncodedForm
    let message = "Hello!"
}

router.get("greeting") { req in
    return Hello() // message=Hello!
}

router.get("greeting2") { req in
    let res = req.response()
    try res.content.encode(Hello(), as: .json)
    return res // {"message":"Hello!"}
}

before​Encode()

mutating func beforeEncode() throws

Called before this Content is encoded, generally for a Response object.

You should use this method to perform any "sanitizing" which you need on the data. For example, you may wish to replace empty strings with a nil, trim() your strings or replace empty arrays with nil. You can also use this method to abort the encoding if something isn't valid. An empty array may indicate an error, for example.

after​Decode()

mutating func afterDecode() throws

Called after this Content is decoded, generally from a Request object.

You should use this method to perform any "sanitizing" which you need on the data. For example, you may wish to replace empty strings with a nil, trim() your strings or replace empty arrays with nil. You can also use this method to abort the decoding if something isn't valid. An empty string may indicate an error, for example.