Request
Every route closure gets passed an instance of Request. This allows you to access information about the request made to your application such as the URI, input data, and session.
Data
Any input sent during the request, such as query, form-encoded, or JSON-encoded data can be accessed from the data property.
request.data["name"]
Order of Importance
Since query and body data are both accessed through the
dataproperty, it is possible that both will contain a value with the same key. In these cases, query data will trump body data.
Polymorphic
Subscripting request data always returns an object that conforms to Polymorphic.
Polymorphic is a common protocol used throughout the framework. It allows for objects of unknown types to be more easily transformed into typed values.
For example, if you are expecting the key age to be sent as input, and for the age to be an Int, you could use the .int property.
guard let age = request.data["age"].int else {
throw Abort.badRequest
}
Path Indexable
Nested values can be easily accessed using comma syntax.
let firstName = request.data["name", "first"].string
You can use a mixture of String and Int to form your path.
let firstUserEmail = request.data["users", 0, "email"].string
Specific Access
If you need to access the query, form-encoded, or JSON-encoded data specifically, you can.
request.data.query // StructuredData
request.data.json // JSON?
request.data.formEncoded // StructuredData?
request.data.mulipart // [String: MultiPart]?
S4
The Request type is based on the request from Open Swift's S4 standards. This means you can pass requests from Vapor directly into any other S4 compatible project.
public var uri: C7.URI
public var version: S4.Version
public var headers: S4.Headers
public var body: S4.Body
public var storage: [String : Swift.Any]
public init(
method: S4.Method,
uri: C7.URI,
version: S4.Version,
headers: S4.Headers,
body: S4.Body
)
Method
The method property contains the HTTP method used by the request.
enum Method {
case delete
case get
case head
case post
case put
case connect
case options
case trace
case patch
case other(method: String)
}
URI
The uri property contains information about the uniform resource identifier used to identify a specific route or resource in your application.
struct URI {
var scheme: String?
var host: String?
var port: Int?
var path: String?
var query: [String: [String?]]
var fragment: String?
}
Headers
The headers property contains a dictionary of all of the request headers by key. The key is case insensitive and can contain one or more values (as per the HTTP spec).
let contentType = request.headers["content-type"]
Body
To access the raw data from the body of the request, use the body property.
let data = request.body
Updated less than a minute ago
