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
ApplicationCore type representing a Vapor application.BCryptDigestCreates and verifies BCrypt hashes. Normally you will not need to initialize one of these classes and you will use the globalBCryptconvenience instead.BootCommandBoots theApplicationthen exits successfully.CORSMiddlewareMiddleware that adds support for CORS settings in request responses. For configuration of this middleware please use theCORSMiddleware.Configurationobject.EndpointCacheHandles the complexities of HTTP caching.ErrorMiddlewareCaptures all errors and transforms them into an internal server error HTTP response.FileMiddlewareServes static files from a public directory.HTTPServerRequestRepresents an HTTP request in an application.ResponseAn HTTP response from a server back to the client.RouteRouteLoggingMiddlewareEmits a log message containing the request method and path to aRequest’s logger. The log level of the message is configurable.RoutesRoutesCommandDisplays all routes registered to theApplication’sRouterin an ASCII-formatted table.ServeCommandBoots the application’s server. Listens forSIGINTandSIGTERMfor graceful shutdown.SessionSessions are a method for associating data with a client accessing your app.SessionsMiddlewareUses HTTP cookies to save and restore sessions for connecting clients.TracingMiddlewareCreates a trace and metadata for every request
Protocols
AbortErrorErrors conforming to this protocol will always be displayed by Vapor to the end-user (even in production mode where most errors are silenced).AnyOptionalTypeType-erasedOptionalTypeAsyncAuthenticatorHelper for creating authentication middleware.AsyncBasicAuthenticatorHelper for creating authentication middleware using the Basic authorization header.AsyncBearerAuthenticatorHelper for creating authentication middleware using the Bearer authorization header.AsyncBodyStreamWriterA type that represents the writable handle of a streamedResponsebodyAsyncCredentialsAuthenticatorHelper for creating authentication middleware using request body contents.AsyncMiddlewareAsyncMiddlewareis placed between the server and your router. It is capable of mutating both incoming requests and outgoing responses.AsyncMiddlewarecan choose to pass requests on to the nextAsyncMiddlewarein a chain, or they can short circuit and return a customResponseif desired.AsyncRequestAuthenticatorHelp for creating authentication middleware based onRequest.AsyncRequestDecodableCan convertRequestto aSelf.AsyncResponderAsyncResponseEncodableCan convertselfto aResponse.AsyncSessionAuthenticatorHelper for creating authentication middleware in conjunction withSessionsMiddleware.AsyncSessionDriverCapable of managing CRUD operations forSessions.AuthenticatableCapable of being authenticated.AuthenticatorHelper for creating authentication middleware.BasicAuthenticatorHelper for creating authentication middleware using the Basic authorization header.BearerAuthenticatorHelper for creating authentication middleware using the Bearer authorization header.BodyStreamWriterA type that represents the writable handle of a streamedResponsebody.CacheCodable key-value pair cache.ClientCodingKeyRepresentableThis is an unwelcome stand-in for theSwift/CodingKeyRepresentableprotocol that appeared in Swift 5.6.ContentConvertible to / from content in an HTTP message.ContentContainerContentDecoderConform a type to this protocol to make it usable for decoding data via Vapor’sContentConfigurationsystem.ContentEncoderConform a type to this protocol to make it usable for encoding data via Vapor’sContentConfigurationsystem.CredentialsAuthenticatorHelper for creating authentication middleware using request body contents.DebuggableErrorDebuggableprovides an interface that allows a type to be more easily debugged in the case of an error.ExtendableTypes conforming toExtendablecan have stored properties added in extension by using theExtendstruct.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 shutdownLockKeyMiddlewareMiddlewareis 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.OptionalTypeCapable of being represented by an optional wrapped type.PasswordHasherRequestAuthenticatorHelp for creating authentication middleware based onRequest.RequestDecodableCan convertRequestto aSelf.ResponderResponseEncodableCan convertselfto aResponse.RouteCollectionGroups collections of routes together for adding to a router.RoutesBuilderServerSessionAuthenticatableModels conforming to this protocol can have their authentication status cached usingSessionAuthenticator.SessionAuthenticatorHelper for creating authentication middleware in conjunction withSessionsMiddleware.SessionDriverCapable of managing CRUD operations forSessions.StorageKeyA key used to store values in aStoragemust conform to this protocol.URLQueryContainerHelper for encoding and decoding data from an HTTP request query string.URLQueryDecoderURLQueryEncoderUpgraderConformance for any struct that performs an HTTP UpgradeValidatableCapable of being validated. Conformance adds a throwingvalidate()method.ValidatorResultViewRenderer
Structures
AbortDefault implementation ofAbortError. You can use this as a convenient method for throwingAbortErrors without having to conform your own error-type toAbortError.AnyAsyncResponseA type erased response useful for routes that can return more than one type.AnyResponseA type erased response useful for routes that can return more than one type.AsyncBasicResponderA basic, async closure-basedResponder.AsyncPasswordHasherBaseNEncodingBasicAuthorizationA basic username and password.BasicResponderA basic, closure-basedResponder.BearerAuthorizationA bearer token.ByteCountlet bytes: ByteCount = “2kb” print(bytes.value) // 2048ClientRequestClientResponseContentConfigurationConfigures whichEncoders andDecoders to use when interacting with data in HTTP messages.DecoderUnwrapperDirectoryConfigurationDirectoryConfigurationrepresents a configured working directory. It can also be used to derive a working directory automatically.DotEnvFileReads dotenv (.env) files and loads them into the current process.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.ErrorSourceA source-code location.ExtendA wrapper around a simple [String: Any] storage dictionary used to implementExtendable.FileRepresents a single file.FileIOFileIOis a convenience wrapper around SwiftNIO’sNonBlockingFileIO.HOTPCreate a one-time password using hash-based message authentication codes.HTTPCookiesA collection ofHTTPCookies.HTTPMediaTypeRepresents an encoded data-format, used in HTTP, HTML, email, and elsewhere.HTTPMediaTypePreferenceRepresents aMediaTypeand its associated preference,q.HTTPMediaTypeSetA collection for efficiently determining if a set of types contains another type.MemorySessionsSimple in-memory sessions implementation.MiddlewaresConfigures an application’s activeMiddleware. Middleware will be used in the order they are added.PlaintextDecoderDecodes data as plaintext, utf8.PlaintextEncoderEncodes data as plaintext, utf8.PlaintextRendererRedirectSpecifies the type of redirect that the client should receive.ResponseCompressionMiddlewareOverrides the response compression settings for a route.RouteNotFoundSessionDataA container for storing data associated with a givenSessionID.SessionIDSessionsConfigurationConfiguration options for sessions.StackTraceStorageA container providing arbitrary storage for extensions of an existing type, designed to obviate the problem of being unable to add stored properties to a type in an extension. Each stored item is keyed by a type conforming toStorageKeyprotocol.TOTPCreate a one-time password using hash-based message authentication codes and taking uniqueness from the time.URIA type for constructing and manipulating (most) Uniform Resource Indicators.URLEncodedFormDecoderDecodes instances ofDecodabletypes fromapplication/x-www-form-urlencodeddata.URLEncodedFormEncoderEncodesEncodableinstances toapplication/x-www-form-urlencodeddata.ValidationValidationResultValidationsValidationsErrorValidationsResultValidatorValidatorResultsViewWebSocketMaxFrameSizeWebSocketUpgraderHandles upgrading an HTTP connection to a WebSocket
Variables
BcryptCreates and verifies BCrypt hashes.
Operators
!(_:)Inverts aValidationx`.&&(_:_:)Combines twoValidators using AND logic, succeeding if bothValidators succeed without error.+(_:_:)Unions two character sets.??(_:_:)Appliesnilcoalescing to a future’s optional and a concrete type.||(_:_:)Combines twoValidators, succeeding if either of theValidators does not fail.
Type Aliases
HTTPStatusLess verbose typealias forHTTPResponseStatus.ValidationKeyVaporSendableMetatype
Enumerations
Base32Base64BasicCodingKeyA basicCodingKeyimplementation.BcryptErrorBindAddressBodyStreamResultCacheExpirationTimeDefines the lifetime of an entry in a cache.EndpointCacheErrorHTTPBodyStreamStrategyDetermines how an incoming HTTP request’s body is collected.HTTPVersionMajorHelpFormatAvailable formatting options for generating debug info forDebuggableerrors.OTPDigestSupported OTP digests.OTPDigitsSupported OTP output sizes.RangeResultType used byRangeandCountvalidators to indicate where a value fell within a range.RedirectTypeSpecifies the type of redirect that the client should receive.