Server-Side Swift
Prerequisites: Async/await, Codable and JSON, Swift Package Manager
Swift runs on Linux, and a mature ecosystem exists for building web services with it. A big attraction for app developers: sharing model types and validation code between an iOS app and its back end.
The best-known framework is Vapor; Hummingbird is a lighter alternative. Both are built on SwiftNIO, Apple's high-performance networking library.
A Vapor API
brew install vapor # or follow the Linux instructions on vapor.codes
vapor new TodoAPI -n
cd TodoAPI
swift run
Routes are defined with closures that receive the request:
import Vapor
struct Todo: Content { // Content = Codable + HTTP encoding
var id: UUID?
var title: String
var done: Bool
}
func routes(_ app: Application) throws {
app.get("health") { _ in
["status": "ok"]
}
app.post("todos") { req async throws -> Todo in
var todo = try req.content.decode(Todo.self)
guard !todo.title.isEmpty else {
throw Abort(.unprocessableEntity, reason: "title is required")
}
todo.id = UUID()
return todo
}
}
$ curl -X POST localhost:8080/todos \
-H "Content-Type: application/json" \
-d '{"title":"Learn Vapor","done":false}'
{"id":"3F2A...","title":"Learn Vapor","done":false}
Contentmakes a type decodable from requests and encodable into responses.- Handlers are
async, so database queries and outgoing HTTP calls don't block the server. Abort(.unprocessableEntity)returns a 422 status with a JSON error.
Databases
Vapor's Fluent ORM maps model classes to tables in PostgreSQL, MySQL, or SQLite, with migrations and typed queries. Queries use parameters, which protects against SQL injection.
Deployment
Server-side Swift apps compile to a single native binary. The standard
deployment is a Docker image built from the official swift base image,
using a multi-stage build that copies only the compiled binary into a
small runtime image — the Vapor template includes a ready-made
Dockerfile.
When to choose it
Server-side Swift makes most sense for teams already writing Swift for Apple platforms. For a team starting fresh, larger back-end ecosystems (Go, Node.js, Python, Java, Ruby) offer more libraries and hosting options.