kingpin-apps/swift-koios
A Swift library for accessing the Koios API, providing comprehensive access to Cardano blockchain data.
Overview
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.
What is Koios?
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
Features
- ✅ 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
Installation
Swift Package Manager
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
Quick Start
Basic Usage (No API Key)
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)")Using API Key
// 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"
)Querying Address Information
// 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)")
}Pool Information
// 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")")
}Transaction Details
// 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)")
}Networks
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)Custom Base URL
// Use custom Koios instance
let koios = try Koios(
network: .mainnet,
basePath: "https://your-custom-koios-instance.com/api/v1"
)Vertical Filtering
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.
Basic Example
// 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"]
)
)
)Without Filtering (Default)
Omit the select parameter to get all fields:
let response = try await koios.client.tip(
Operations.Tip.Input()
)
// Returns all available fieldsBenefits
- 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
Available on All GET Endpoints
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.
Error Handling
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)")
}Available Endpoints
SwiftKoios provides access to all Koios API endpoints:
Network
tip()- Get current chain tipgenesis()- Get genesis parameterstotals()- Get historical tokenomicsparamUpdates()- Get parameter updatesepochInfo()- Get epoch information
Blocks
blocks()- Get block listblockInfo()- Get block informationblockTxs()- Get block transactions
Transactions
txInfo()- Get transaction detailstxMetadata()- Get transaction metadatatxCbor()- Get raw transaction CBORtxStatus()- Get transaction confirmations
Addresses
addressInfo()- Get address informationaddressTxs()- Get address transactionsaddressAssets()- Get address assets
Assets
assetList()- Get native asset listassetInfo()- Get asset informationassetHistory()- Get asset mint/burn historyassetAddresses()- Get asset holder addresses
Pool
poolList()- Get all poolspoolInfo()- Get pool informationpoolDelegators()- Get pool delegatorspoolHistory()- Get pool historypoolMetadata()- Get pool metadata
Governance (Conway Era)
drepList()- Get DRep listdrepInfo()- Get DRep informationproposalList()- Get governance proposalscommitteeInfo()- Get committee information
Scripts
scriptInfo()- Get script informationdatumInfo()- Get datum information
Testing
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 testContributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Development Setup
# Clone the repository
git clone https://github.com/Kingpin-Apps/swift-koios
cd swift-koios
# Run tests
swift test
# Build the project
swift buildDocumentation
Official Koios Documentation
Cardano Resources
Swift OpenAPI
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Koios Team for providing the excellent API
- Cardano Community for the amazing ecosystem
- Swift OpenAPI Generator for code generation tools
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Package Metadata
Repository: kingpin-apps/swift-koios
Default branch: main
README: README.md