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 BCryptDigestCreates and verifies BCrypt hashes. Normally you will not need to initialize one of these classes and you will use the globalBCryptconvenience instead.class BootCommandBoots theApplicationthen exits successfully.class CORSMiddlewareMiddleware that adds support for CORS settings in request responses. For configuration of this middleware please use theCORSMiddleware.Configurationobject.class EndpointCacheHandles the complexities of HTTP caching.class ErrorMiddlewareCaptures all errors and transforms them into an internal server error HTTP response.class FileMiddlewareServes static files from a public directory.class HTTPServerclass RequestRepresents an HTTP request in an application.class ResponseAn HTTP response from a server back to the client.class Routeclass RouteLoggingMiddlewareEmits a log message containing the request method and path to aRequest’s logger. The log level of the message is configurable.class Routesclass RoutesCommandDisplays all routes registered to theApplication’sRouterin an ASCII-formatted table.class ServeCommandBoots the application’s server. Listens forSIGINTandSIGTERMfor graceful shutdown.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 AsyncAuthenticatorHelper for creating authentication middleware.protocol AsyncBasicAuthenticatorHelper for creating authentication middleware using the Basic authorization header.protocol AsyncBearerAuthenticatorHelper for creating authentication middleware using the Bearer authorization header.protocol AsyncBodyStreamWriterA type that represents the writable handle of a streamedResponsebodyprotocol AsyncCredentialsAuthenticatorHelper for creating authentication middleware using request body contents.protocol 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.protocol AsyncRequestAuthenticatorHelp for creating authentication middleware based onRequest.protocol AsyncRequestDecodableCan convertRequestto aSelf.protocol AsyncResponderprotocol AsyncResponseEncodableCan convertselfto aResponse.protocol AsyncSessionAuthenticatorHelper for creating authentication middleware in conjunction withSessionsMiddleware.protocol AsyncSessionDriverCapable of managing CRUD operations forSessions.protocol AuthenticatableCapable of being authenticated.protocol AuthenticatorHelper for creating authentication middleware.protocol BasicAuthenticatorHelper for creating authentication middleware using the Basic authorization header.protocol BearerAuthenticatorHelper for creating authentication middleware using the Bearer authorization header.protocol BodyStreamWriterA type that represents the writable handle of a streamedResponsebody.protocol 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 CredentialsAuthenticatorHelper for creating authentication middleware using request body contents.protocol 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 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 LockKeyprotocol 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 PasswordHasherprotocol RequestAuthenticatorHelp for creating authentication middleware based onRequest.protocol RequestDecodableCan convertRequestto aSelf.protocol Responderprotocol ResponseEncodableCan convertselfto aResponse.protocol RouteCollectionGroups collections of routes together for adding to a router.protocol RoutesBuilderprotocol Serverprotocol 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 StorageKeyA key used to store values in aStoragemust conform to this protocol.protocol URLQueryContainerHelper for encoding and decoding data from an HTTP request query string.protocol URLQueryDecoderprotocol URLQueryEncoderprotocol UpgraderConformance for any struct that performs an HTTP Upgradeprotocol 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 AnyAsyncResponseA type erased response useful for routes that can return more than one type.struct AnyResponseA type erased response useful for routes that can return more than one type.struct AsyncBasicResponderA basic, async closure-basedResponder.struct AsyncPasswordHasherstruct BaseNEncodingstruct BasicAuthorizationA basic username and password.struct BasicResponderA basic, closure-basedResponder.struct BearerAuthorizationA bearer token.struct ByteCountlet bytes: ByteCount = “2kb” print(bytes.value) // 2048struct ClientRequeststruct ClientResponsestruct ContentConfigurationConfigures whichEncoders andDecoders to use when interacting with data in HTTP messages.struct DecoderUnwrapperstruct 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 FileIOFileIOis a convenience wrapper around SwiftNIO’sNonBlockingFileIO.struct HOTPCreate a one-time password using hash-based message authentication codes.struct 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 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 PlaintextRendererstruct RedirectSpecifies the type of redirect that the client should receive.struct ResponseCompressionMiddlewareOverrides the response compression settings for a route.struct RouteNotFoundstruct SessionDataA container for storing data associated with a givenSessionID.struct SessionIDstruct SessionsConfigurationConfiguration options for sessions.struct StackTracestruct StorageA 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.struct TOTPCreate a one-time password using hash-based message authentication codes and taking uniqueness from the time.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 ValidationResultstruct Validationsstruct ValidationsErrorstruct ValidationsResultstruct Validatorstruct ValidatorResultsstruct Viewstruct WebSocketMaxFrameSizestruct WebSocketUpgraderHandles upgrading an HTTP connection to a WebSocket
Variables
var Bcrypt: BCryptDigestCreates and verifies BCrypt hashes.
Operators
func ! <T>(Validator<T>) -> Validator<T>Inverts aValidationx`.func &&(_:_:)Combines twoValidators using AND logic, succeeding if bothValidators succeed without error.func + (CharacterSet, CharacterSet) -> CharacterSetUnions two character sets.func ?? <T>(EventLoopFuture<T?>, T) -> EventLoopFuture<T>Appliesnilcoalescing to a future’s optional and a concrete type.func ||(_:_:)Combines twoValidators, succeeding if either of theValidators does not fail.
Type Aliases
typealias CodingKeyRepresentabletypealias HTTPStatusLess verbose typealias forHTTPResponseStatus.typealias ValidationKeytypealias VaporSendableMetatype
Enumerations
enum Base32enum Base64enum BasicCodingKeyA basicCodingKeyimplementation.enum BcryptErrorenum BindAddressenum BodyStreamResultenum CacheExpirationTimeDefines the lifetime of an entry in a cache.enum EndpointCacheErrorenum HTTPBodyStreamStrategyDetermines how an incoming HTTP request’s body is collected.enum HTTPVersionMajorenum HelpFormatAvailable formatting options for generating debug info forDebuggableerrors.enum OTPDigestSupported OTP digests.enum OTPDigitsSupported OTP output sizes.enum RangeResultType used byRangeandCountvalidators to indicate where a value fell within a range.enum RedirectTypeSpecifies the type of redirect that the client should receive.