Creating Mock API Local Server with Swift
·2 mins

📡 Creating Mock API Local Server with Swift
This guide shows you how to quickly spin up a Mock API server using Swift and Swifter, a simple HTTP server engine for Swift.
🛠️ Step 1: Create a Swift Package Project #
In your terminal, run:
swift package init --type executable
This creates a new Swift package with an executable target.
📦 Step 2: Update Package.swift
#
Replace the contents of your Package.swift
file with the following:
// swift-tools-version:5.7
import PackageDescription
let package = Package(
name: "MockAPISwift",
dependencies: [
.package(url: "https://github.com/httpswift/swifter.git", from: "1.5.0")
],
targets: [
.executableTarget(
name: "MockAPISwift",
dependencies: [
.product(name: "Swifter", package: "swifter")
]
),
]
)
📂 Step 3: Edit main.swift
#
Navigate to Sources/main.swift
and replace the contents with:
import Foundation
import Swifter
let server = HttpServer()
server["/home"] = { request in
let json = """
[
{ \"id\": 1, \"product\": \"Test1\" },
{ \"id\": 2, \"product\": \"Test2\" }
]
"""
return HttpResponse.ok(.text(json))
}
do {
try server.start(8082)
print("Server has started on port 8082. Try to connect now...")
RunLoop.main.run()
} catch {
print("Server start error: \(error)")
}
🌐 Example API Endpoint #
After running the server, you can access:
http://localhost:8082/home
It will return a mock JSON response.
🚀 Step 4: Run Your Server #
In the terminal, run:
swift run
🛠 If swift run
doesn’t work: #
Try cleaning the project and running again:
swift package clean
swift run
⚠️ Debugging Tips #
- If the server doesn’t respond, try changing the port number in
server.start(...)
- Make sure nothing else is using that port (like another local server)
- Check for typos in the JSON string or endpoint path
✅ You’re all set to mock APIs locally with Swift!