Framework
Vapor
Vapor is a framework for building server applications, APIs and websites in Swift. It provides a safe, performant and scalable foundation for building large complex backends.
Overview
Vapor provides many of the parts needed for building full-featured applications.
For more details, check out the main docs.
Topics
Classes
class ApplicationCore type representing a Vapor application.class CORSMiddlewareMiddleware that adds support for CORS settings in request responses. For configuration of this middleware please use theCORSMiddleware.Configurationobject.actor EndpointCacheHandles the complexities of HTTP caching.class ErrorMiddlewareCaptures all errors and transforms them into an internal server error HTTP response.actor FileETagHashCacheCaches the content hashes used for advanced ETag comparison.class FileMiddlewareServes static files from a public directory.class MetricsMiddlewareCreates metrics for every requestclass RouteLoggingMiddlewareEmits a log message containing the request method and path to aRequest’s logger. The log level of the message is configurable.class SessionSessions are a method for associating data with a client accessing your app.class SessionsMiddlewareUses HTTP cookies to save and restore sessions for connecting clients.class TracingMiddlewareCreates a trace and metadata for every request
Protocols
protocol AbortErrorErrors conforming to this protocol will always be displayed by Vapor to the end-user (even in production mode where most errors are silenced).protocol AnyOptionalTypeType-erasedOptionalTypeprotocol AuthenticatableA protocol to which a type may conform to enable use of that type for authentication.protocol BasicAuthenticatorHTTP Basic Auth implementation ofRequestAuthenticator. Makes it easy to implement basic auth for your ownAuthenticatabletypes.protocol BearerAuthenticatorprotocol CacheCodable key-value pair cache.protocol Clientprotocol ContentConvertible to / from content in an HTTP message.protocol ContentContainerprotocol ContentDecoderConform a type to this protocol to make it usable for decoding data via Vapor’sContentConfigurationsystem.protocol ContentEncoderConform a type to this protocol to make it usable for encoding data via Vapor’sContentConfigurationsystem.protocol CredentialsAuthenticatorProtocol for authenticators that use a credentials type to authenticate. SeeCredentialsAuthenticatorfor more information. Designed for use with HTML forms, works with JSON as wellprotocol DebuggableErrorDebuggableprovides an interface that allows a type to be more easily debugged in the case of an error.protocol ExtendableTypes conforming toExtendablecan have stored properties added in extension by using theExtendstruct.protocol HTTPBodyWriterProtocol for writing HTTP response bodies.protocol LifecycleHandlerProvides a way to hook into lifecycle events of a Vapor application. You can register your handlers with theApplicationto be notified when the application is about to start up, has started up and is about to shutdownprotocol MiddlewareMiddlewareis placed between the server and your router. It is capable of mutating both incoming requests and outgoing responses.Middlewarecan choose to pass requests on to the nextMiddlewarein a chain, or they can short circuit and return a customResponseif desired.protocol OptionalTypeCapable of being represented by an optional wrapped type.protocol RequestAuthenticatorHelper for creating authentication middleware.protocol RequestBodyReaderReads an HTTP request body, pulled straight off the connection with backpressure (the server stops reading until the handler asks for more). Implementations come from the HTTP server layer.protocol RequestDecodableCan convertRequestto aSelf.protocol Responderprotocol ResponseEncodableCan convertselfto aResponse.protocol RouteCollectionGroups collections of routes together for adding to a router.protocol RoutesBuilderprotocol ServerA server that can handle HTTP requests.protocol SessionAuthenticatableModels conforming to this protocol can have their authentication status cached usingSessionAuthenticator.protocol SessionAuthenticatorHelper for creating authentication middleware in conjunction withSessionsMiddleware.protocol SessionDriverCapable of managing CRUD operations forSessions.protocol URLQueryContainerHelper for encoding and decoding data from an HTTP request query string.protocol URLQueryDecoderprotocol URLQueryEncoderprotocol ValidatableCapable of being validated. Conformance adds a throwingvalidate()method.protocol ValidatorResultprotocol ViewRenderer
Structures
struct AbortDefault implementation ofAbortError. You can use this as a convenient method for throwingAbortErrors without having to conform your own error-type toAbortError.struct AnyResponseA type erased response useful for routes that can return more than one type.struct BaseNEncodingstruct BasicAuthorizationA basic username and password.struct BasicResponderA basic, async closure-basedResponder.struct BearerAuthorizationA bearer token.struct BlackholeClientType that conforms toClientbut does nothing and throws an error when used. Can be useful for testing Used when theHTTPClientpackage trait is disabledstruct ByteCountlet bytes: ByteCount = “2kb” print(bytes.value) // 2048struct ClientRequeststruct ClientResponsestruct ContentConfigurationConfigures whichEncoders andDecoders to use when interacting with data in HTTP messages.struct DirectoryConfigurationDirectoryConfigurationrepresents a configured working directory. It can also be used to derive a working directory automatically.struct DotEnvFileReads dotenv (.env) files and loads them into the current process.struct EnvironmentThe environment the application is running in, i.e., production, dev, etc. AllContainers will have anEnvironmentthat can be used to dynamically register and configure services.struct ErrorSourceA source-code location.struct ExtendA wrapper around a simple[String: Any]storage dictionary used to implementExtendable.struct FileRepresents a single file.struct FileIOstruct HTTPCookiesA collection ofHTTPCookies.struct HTTPMediaTypeRepresents an encoded data-format, used in HTTP, HTML, email, and elsewhere.struct HTTPMediaTypePreferenceRepresents aMediaTypeand its associated preference,q.struct HTTPMediaTypeSetA collection for efficiently determining if a set of types contains another type.struct HTTPVersionA structure representing a HTTP version.struct MemorySessionsSimple in-memory sessions implementation.struct MiddlewaresConfigures an application’s activeMiddleware. Middleware will be used in the order they are added.struct PlaintextDecoderDecodes data as plaintext, utf8.struct PlaintextEncoderEncodes data as plaintext, utf8.struct PlaintextRendererAViewRendererthat serves views from files on disk, without any templating.struct RedirectSpecifies the type of redirect that the client should receive.struct RequestRepresents an HTTP request in an application.struct RequestBodyAlreadyBeingReadThrown when the request body is read from two tasks at once. It is a single-consumer stream, so this is a programmer error, surfaced as a 500 rather than silently reporting an empty end-of-body.struct RequestBodyPartiallyConsumedThrown bycollect(max:)when something already took bytes off the stream.struct RequestBodyReadFailedThrown by a read on a stream whose earlier read failed at the transport.struct RequestBodyTransportFailedThrown by the read that finds the request body’s transport has failed: the client hung up part-way through the body, sent fewer bytes than it declared, or sent something the HTTP parser rejected.struct ResponseAn HTTP response from a server back to the client.struct ResponseCompressionMiddlewareOverrides the response compression settings for a route.struct Routestruct RouteNotFoundstruct RoutesThe routes registered on anApplication.struct ServerConfigurationstruct SessionDataA container for storing data associated with a givenSessionID.struct SessionIDstruct SessionsConfigurationConfiguration options for sessions.struct SocketAddressAn address a socket is bound to, or that a peer connected from.struct URIA type for constructing and manipulating (most) Uniform Resource Indicators.struct URLEncodedFormDecoderDecodes instances ofDecodabletypes fromapplication/x-www-form-urlencodeddata.struct URLEncodedFormEncoderEncodesEncodableinstances toapplication/x-www-form-urlencodeddata.struct Validationstruct ValidationCharacterSetstruct ValidationResultstruct Validationsstruct ValidationsErrorstruct ValidationsResultstruct Validatorstruct ValidatorResultsstruct View
Operators
func ! <T>(Validator<T>) -> Validator<T>Inverts aValidationx`.func &&(_:_:)Combines twoValidators using AND logic, succeeding if bothValidators succeed without error.func + (ValidationCharacterSet, ValidationCharacterSet) -> ValidationCharacterSetUnions two character sets.func ||(_:_:)Combines twoValidators, succeeding if either of theValidators does not fail.
Type Aliases
Enumerations
enum Base32enum Base64enum BasicCodingKeyA basicCodingKeyimplementation.enum BindAddressenum BodySizeLimitHow much of a request bodycollect(max:)and its relatives will buffer.enum CacheExpirationTimeDefines the lifetime of an entry in a cache.enum EndpointCacheErrorenum HelpFormatAvailable formatting options for generating debug info forDebuggableerrors.enum RangeResultType used byRangeandCountvalidators to indicate where a value fell within a range.enum ServerErrorErrors thrown when aServerfails to start.