Vapor Documentation

Class Request

public final class Request: CustomStringConvertible  

Represents an HTTP request in an application.

%359 Request Request CustomStringConvertible CustomStringConvertible Request->CustomStringConvertible RequestDecodable RequestDecodable Request->RequestDecodable AsyncRequestDecodable AsyncRequestDecodable Request->AsyncRequestDecodable

Nested Types

Request.Authentication

Request helper for storing and fetching authenticated objects.

Request.Password
Request.Body

Conforms To

AsyncRequestDecodable

Can convert Request to a Self.

RequestDecodable

Can convert Request to a Self.

CustomStringConvertible

Initializers

init(application:​method:​url:​version:​headers:​collected​Body:​remote​Address:​logger:​byte​Buffer​Allocator:​on:​)

public convenience init(
        application: Application,
        method: HTTPMethod = .GET,
        url: URI = "/",
        version: HTTPVersion = .init(major: 1, minor: 1),
        headers: HTTPHeaders = .init(),
        collectedBody: ByteBuffer? = nil,
        remoteAddress: SocketAddress? = nil,
        logger: Logger = .init(label: "codes.vapor.request"),
        byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
        on eventLoop: EventLoop
    )  

init(application:​method:​url:​version:​headers​NoUpdate:​collected​Body:​remote​Address:​logger:​byte​Buffer​Allocator:​on:​)

public init(
        application: Application,
        method: HTTPMethod,
        url: URI,
        version: HTTPVersion = .init(major: 1, minor: 1),
        headersNoUpdate headers: HTTPHeaders = .init(),
        collectedBody: ByteBuffer? = nil,
        remoteAddress: SocketAddress? = nil,
        logger: Logger = .init(label: "codes.vapor.request"),
        byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
        on eventLoop: EventLoop
    )  

Properties

auth

public var auth: Authentication  

Helper for accessing authenticated objects. See Authenticator for more information.

cache

public var cache: Cache  

client

public var client: Client  

password

public var password: Password  

application

public let application: Application

method

public var method: HTTPMethod

The HTTP method for this request.

httpReq.method = .GET

url

public var url: URI

The URL used on this request.

version

public var version: HTTPVersion

The version for this HTTP request.

headers

public var headers: HTTPHeaders

The header fields for this HTTP request. The "Content-Length" and "Transfer-Encoding" headers will be set automatically when the body property is mutated.

route

public var route: Route? 

Route object we found for this request. This holds metadata that can be used for (for example) Metrics.

req.route?.description // "GET /hello/:name"

peer​Address

public var peerAddress: SocketAddress?  

We try to determine true peer address if load balacer or reversed proxy provided info in headers

Priority of getting value from headers is as following:

  1. try the "Forwarded" header (e.g. for=192.0.2.60; proto=http; by=203.0.113.43)
  2. try the "X-Forwarded-For" header (e.g. client_IP, proxy1_IP, proxy2_IP)
  3. fallback to the socket's remote address provided by SwiftNIO ( e.g. 192.0.2.60:62934) in 1. and 2. will use port 80 as default port, and 3. will have port number provided by NIO if any

query

public var query: URLQueryContainer  

content

public var content: ContentContainer  

This container is used to read your Decodable type using a ContentDecoder implementation. If no ContentDecoder is provided, a Request's Content-Type header is used to select a registered decoder.

logger

public var logger: Logger

This Logger from Apple's swift-log Package is preferred when logging in the context of handing this Request. Vapor already provides metadata to this logger so that multiple logged messages can be traced back to the same request.

body

public var body: Body  

cookies

public var cookies: HTTPCookies  

Get and set HTTPCookies for this HTTPRequest This accesses the "Cookie" header.

description

public var description: String  

See CustomStringConvertible

remote​Address

public let remoteAddress: SocketAddress? 

The address from which this HTTP request was received by SwiftNIO. This address may not represent the original address of the peer, especially if Vapor receives its requests through a reverse-proxy such as nginx.

event​Loop

public let eventLoop: EventLoop

The EventLoop which is handling this Request. The route handler and any relevant middleware are invoked in this event loop.

parameters

public var parameters: Parameters

A container containing the route parameters that were captured when receiving this request. Use this container to grab any non-static parameters from the URL, such as model IDs in a REST API.

storage

public var storage: Storage

This container is used as arbitrary request-local storage during the request-response lifecycle.Z

byte​Buffer​Allocator

public var byteBufferAllocator: ByteBufferAllocator

session

public var session: Session  

Returns the current Session or creates one.

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

Returns

Session for this Request.

has​Session

public var hasSession: Bool  

fileio

public var fileio: FileIO  

view

public var view: ViewRenderer  

Methods

decode​Request(_:​)

@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
    public static func decodeRequest(_ request: Request) async throws -> Request  

web​Socket(max​Frame​Size:​should​Upgrade:​on​Upgrade:​)

public func webSocket(
        maxFrameSize: WebSocketMaxFrameSize = .`default`,
        shouldUpgrade: @escaping ((Request) async throws -> HTTPHeaders?) = { _ in [:] },
        onUpgrade: @escaping (Request, WebSocket) async -> ()
    ) -> Response  

Upgrades an existing request to a websocket connection

redirect(to:​type:​)

public func redirect(to location: String, type: RedirectType = .normal) -> 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.

decode​Request(_:​)

public static func decodeRequest(_ request: Request) -> EventLoopFuture<Request>  

web​Socket(max​Frame​Size:​should​Upgrade:​on​Upgrade:​)

public func webSocket(
         maxFrameSize: WebSocketMaxFrameSize = .`default`,
         shouldUpgrade: @escaping ((Request) -> EventLoopFuture<HTTPHeaders?>) = {
             $0.eventLoop.makeSucceededFuture([:])
         },
         onUpgrade: @escaping (Request, WebSocket) -> ()
     ) -> Response