Request

public final class Request : ContainerAlias, DatabaseConnectable, HTTPMessageContainer, RequestCodable, CustomStringConvertible, CustomDebugStringConvertible

Request is a service-container wrapper around an HTTPRequest.

Use Request to access information about the HTTPRequest (req.http).

print(req.http.url.path) // "/hello"

You can also use Request to create services you may need while generating a response (req.make()).

let client = try req.make(Client.self)
print(client) // Client
client.get("http://vapor.codes")

Request also carries a ParametersContainer for routing. Use parameters to fetch parameterized values.

router.get("hello", String.parameter) { req -> String in
    let name = try req.parameters.next(String.self)
    return "Hello, \(name)!"
}

Request is DatabaseConnectable, meaning you can use it in-place of an actual DatabaseConnection. When used as a connection, the request will fetch a connection from the event loop’s connection pool and cache the connection for the lifetime of the request.

let users = User.query(on: req).all()

See HTTPRequest, Container, ParameterContainer, and DatabaseConnectable for more information.

  • The wrapped HTTPRequest.

    print(req.http.url.path) // "/hello"
    

    Declaration

    Swift

    public var http: HTTPRequest
  • This Request‘s parent container. This is normally the event loop. The Request will redirect all calls to create services to this container.

    Declaration

    Swift

    public let sharedContainer: Container
  • This request’s private container. Use this container to create services that will be cached only for the lifetime of this request. For all other services, use the request directly.

    let authCache = try req.privateContainer.make(AuthCache.self)
    

    Declaration

    Swift

    public let privateContainer: SubContainer
  • Helper for encoding and decoding data from an HTTP request query string.

    let flags = try req.query.decode(Flags.self)
    print(flags) // Flags
    

    This helper can also decode single values from specific key paths.

    let name = try req.query.get(String.self, at: "user", "name")
    print(name) // String
    

    See QueryContainer methods for more information.

    Declaration

    Swift

    public var query: QueryContainer { get }
  • Helper for encoding and decoding Content from an HTTP message.

    This helper can encode data to the HTTP message. Uses the Content’s default media type if none is supplied.

    try req.content.encode(user)
    

    This helper can also decode data from the HTTP message.

    let user = try req.content.decode(User.self)
    print(user) /// Future<User>
    

    See ContentContainer methods for more information.

    Declaration

    Swift

    public var content: ContentContainer<Request> { get }
  • Creates a Response on the same container as this Request.

    router.get("greeting2") { req in
        let res = req.response()
        try res.content.encode("hello", as: .plaintext)
        return res
    }
    

    Declaration

    Swift

    public func response(http: HTTPResponse = .init()) -> Response

    Parameters

    http

    Optional HTTPResponse to use.

    Return Value

    A new, empty 200 OK Response on the same container as the current Request.

  • Generate a Response for a HTTPBody convertible object using the supplied MediaType.

    router.get("html") { req in
        return req.response("<h1>Hello, world!</h1>", as: .html)
    }
    

    Declaration

    Swift

    public func response(_ body: LosslessHTTPBodyRepresentable, as contentType: MediaType = .plainText) -> Response

    Parameters

    type

    The type of data to return the container with.

  • See DatabaseConnectable.

    Declaration

    Swift

    public func databaseConnection<D>(to database: DatabaseIdentifier<D>?) -> Future<D.Connection> where D : Database
  • See req.response(http:).

    Declaration

    Swift

    @available(*, deprecated, renamed: "response(http:﹚")
    public func makeResponse(http: HTTPResponse = .init()) -> Response
  • See req.response(_ body:as:).

    Declaration

    Swift

    @available(*, deprecated, renamed: "response(_body:as:﹚")
    public func makeResponse(_ body: LosslessHTTPBodyRepresentable, as contentType: MediaType = .plainText) -> Response
  • Creates a redirect Response.

    router.get("redirect") { req in
        return req.redirect(to: "https://vapor.codes")
    }
    

    Set type to ‘.permanently’ to allow caching to automatically redirect from browsers. Defaulting to non-permanent to prevent unexpected caching.

    Declaration

    Swift

    public func redirect(to location: String, type: RedirectType = .normal) -> Response
  • Returns the current Session or creates one.

    router.get("session") { req -> String in
        let session = try req.session()
        session["name"] = "Vapor"
        return "Session set"
    }
    

    Note

    SessionsMiddleware must be added and enabled.

    Declaration

    Swift

    public func session() throws -> Session

    Return Value

    Session for this Request.

  • Destroys the current session, if one exists.

    Declaration

    Swift

    public func destroySession() throws
  • Creates a FileIO for this Request.

    let data = try req.fileio().read(file: "/path/to/file.txt")
    print(data) // Future<Data>
    

    See FileIO for more information.

    Declaration

    Swift

    public func fileio() throws -> FileIO
  • If you are simply looking to serve files from your public directory, it may be useful to look at ‘FileMiddleware’ instead.

    Use this to initialize a file response for the exact file path. If using from a public folder for example, the file name should be appended to the public directory, ie: drop.publicDir + "myFile.cool"

    If none match represents an ETag that will be used to check if the file has changed since the last load by the client. This allows clients like browsers to cache their files and avoid downloading resources unnecessarily. Most often calculated w/ https://tools.ietf.org/html/rfc7232#section-3.2

    For an example of how this is used, look at ‘FileMiddleware’.

    See FileIO for more information.

    Declaration

    Swift

    public func streamFile(at path: String) throws -> Future<Response>
  • Creates a ViewRenderer.

    router.get("home") { req -> Future<View> in
        return try req.view().make("home", ["message", "Hello, world!"])
    }
    

    Declaration

    Swift

    public func view() throws -> ViewRenderer