A Swift library for accessing the Koios API, providing comprehensive access to Cardano blockchain data.
SwiftKoios is a Swift Package Manager library that provides a type-safe, async/await interface to the Koios API. It allows iOS, macOS, watchOS, and tvOS applications to easily access Cardano blockchain data including transactions, blocks, addresses, stake pools, governance information, and more.
The library is built using Swift OpenAPI Generator, ensuring type safety and automatic code generation from the official Koios OpenAPI specification.
Koios is a decentralized and elastic RESTful query layer for exploring Cardano blockchain data. It provides:
- Comprehensive Data Access: Query transactions, blocks, addresses, UTxOs, stake pools, governance data, and more
- Multiple Networks: Support for Mainnet, Preprod, Preview, Guild, and Sanchonet
- High Performance: Optimized queries with caching and load balancing
- Open Source: Community-driven development and maintenance
- Premium Features: Enhanced rate limits and priority support with API keys
- âś… Complete API Coverage: Access to all Koios endpoints
- âś… Type-Safe: Generated Swift types from OpenAPI specification
- âś… Async/Await: Modern Swift concurrency support
- âś… Multi-Platform: iOS 14+, macOS 13+, watchOS 7+, tvOS 14+
- âś… Network Support: Mainnet, Preprod, Preview, Guild, Sanchonet
- âś… Authentication: Optional API key support for enhanced limits
- âś… Error Handling: Comprehensive error types and handling
- âś… Testing: Mock transport for unit testing
Add SwiftKoios to your Package.swift file:
dependencies: [
.package(url: "https://github.com/Kingpin-Apps/swift-koios", from: "1.0.0")
]Or add it through Xcode:
- File → Add Package Dependencies
- Enter the repository URL
- Select version and add to your target
import SwiftKoios
// Create a client for Mainnet
let koios = try Koios(network: .mainnet)
// Query chain tip
let tip = try await koios.client.tip()
let tipData = try tip.ok.body.json
print("Current epoch: \(tipData[0].epochNo)")
// Query genesis parameters
let genesis = try await koios.client.genesis()
let genesisData = try genesis.ok.body.json
print("Network: \(genesisData[0].networkid)")// With explicit API key
let koios = try Koios(
network: .mainnet,
apiKey: "your-api-key-here"
)
// From environment variable
let koios = try Koios(
network: .mainnet,
environmentVariable: "KOIOS_API_KEY"
)// Get address information
let addressInfo = try await koios.client.addressInfo(
body: .init([
.init("addr1qy2jt0qpqz2z2z3z2z2z2z2z2z2z2z2z2z2z2z2z2z2z2z2z2z2z2z2z")
])
)
let addresses = try addressInfo.ok.body.json
for address in addresses {
print("Balance: \(address.balance ?? "0") lovelace")
print("UTxO count: \(address.utxoSet?.count ?? 0)")
}// Get pool information
let poolInfo = try await koios.client.poolInfo(
body: .init([
.init("pool1abc123...") // Bech32 pool ID
])
)
let pools = try poolInfo.ok.body.json
for pool in pools {
print("Pool: \(pool.poolIdBech32 ?? "unknown")")
print("Ticker: \(pool.metaJson?.ticker ?? "N/A")")
print("Live stake: \(pool.liveStake ?? "0")")
}// Get transaction information
let txInfo = try await koios.client.txInfo(
body: .init(.init(txHashes: [
"abc123def456..." // Transaction hash
]))
)
let transactions = try txInfo.ok.body.json
for tx in transactions {
print("TX Hash: \(tx.txHash)")
print("Fee: \(tx.fee ?? "0") lovelace")
print("Block height: \(tx.blockHeight)")
}SwiftKoios supports multiple Cardano networks:
// Mainnet (default)
let mainnet = try Koios(network: .mainnet)
// Preprod testnet
let preprod = try Koios(network: .preprod)
// Preview testnet
let preview = try Koios(network: .preview)
// Guild network
let guild = try Koios(network: .guild)
// Sanchonet (Conway testnet)
let sancho = try Koios(network: .sancho)// Use custom Koios instance
let koios = try Koios(
network: .mainnet,
basePath: "https://your-custom-koios-instance.com/api/v1"
)SwiftKoios supports the select query parameter for vertical filtering, allowing you to specify which fields to return in API responses. This reduces bandwidth usage and improves performance by only returning the fields you need.
// Request only specific fields
let response = try await koios.client.tip(
Operations.Tip.Input(
query: .init(
select: ["hash", "epoch_no", "block_height"]
)
)
)
// Generates: GET /tip?select=hash,epoch_no,block_height
// Get blocks with selected fields
let blocksResponse = try await koios.client.blocks(
Operations.Blocks.Input(
query: .init(
select: ["hash", "epoch_no", "tx_count", "block_time"]
)
)
)Omit the select parameter to get all fields:
let response = try await koios.client.tip(
Operations.Tip.Input()
)
// Returns all available fields- Reduce bandwidth: Only fetch the data you need
- Improve performance: Smaller responses mean faster processing
- Optimize memory: Less data to parse and store
- Clear intent: Explicitly state which fields you're using
The select parameter works on all GET endpoints that return data, including:
- Network endpoints (tip, genesis, totals, etc.)
- Epoch endpoints
- Block, transaction, address, asset endpoints
- Pool, governance, and script endpoints
See Examples/SelectParameterExample.swift for complete working examples.
do {
let tip = try await koios.client.tip()
let tipData = try tip.ok.body.json
// Handle success
} catch let error as KoiosError {
switch error {
case .invalidBasePath(let message):
print("Invalid base path: \(message)")
case .missingAPIKey(let message):
print("Missing API key: \(message)")
case .valueError(let message):
print("Value error: \(message)")
}
} catch {
print("Other error: \(error)")
}SwiftKoios provides access to all Koios API endpoints:
tip()- Get current chain tipgenesis()- Get genesis parameterstotals()- Get historical tokenomicsparamUpdates()- Get parameter updatesepochInfo()- Get epoch information
blocks()- Get block listblockInfo()- Get block informationblockTxs()- Get block transactions
txInfo()- Get transaction detailstxMetadata()- Get transaction metadatatxCbor()- Get raw transaction CBORtxStatus()- Get transaction confirmations
addressInfo()- Get address informationaddressTxs()- Get address transactionsaddressAssets()- Get address assets
assetList()- Get native asset listassetInfo()- Get asset informationassetHistory()- Get asset mint/burn historyassetAddresses()- Get asset holder addresses
poolList()- Get all poolspoolInfo()- Get pool informationpoolDelegators()- Get pool delegatorspoolHistory()- Get pool historypoolMetadata()- Get pool metadata
drepList()- Get DRep listdrepInfo()- Get DRep informationproposalList()- Get governance proposalscommitteeInfo()- Get committee information
scriptInfo()- Get script informationdatumInfo()- Get datum information
SwiftKoios includes comprehensive test support with mock data:
import SwiftKoios
// Create mock client for testing
let mockKoios = try Koios(
network: .mainnet,
apiKey: "test-key",
client: Client(
serverURL: URL(string: "https://api.koios.rest/api/v1")!,
transport: MockTransport() // Your mock transport
)
)Run tests:
swift testContributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
# Clone the repository
git clone https://github.com/Kingpin-Apps/swift-koios
cd swift-koios
# Run tests
swift test
# Build the project
swift buildThis project is licensed under the MIT License - see the LICENSE file for details.
- Koios Team for providing the excellent API
- Cardano Community for the amazing ecosystem
- Swift OpenAPI Generator for code generation tools
- Issues: GitHub Issues
- Discussions: GitHub Discussions