Swisspost

A Ruby gem for interacting with Swiss Post APIs, providing address validation, barcode generation, and price calculation services.

Installation

Install the gem and add to the application's Gemfile by executing:

bundle add swisspost

If bundler is not being used to manage dependencies, install the gem by executing:

gem install swisspost

Usage

Configuration

Before using any of the services, you need to configure your Swiss Post API credentials:

require 'swisspost'

# Configure your API credentials (required for all services)
Swisspost.configure do |config|
  config.client_id = 'your_client_id'
  config.client_secret = 'your_client_secret'
  config.api_key = 'your_api_key' # Required for price service
end

Address Validation Service

Validate Swiss addresses using the Swiss Post address validation API:

# Create an address object
address = Swisspost::Model::Address.new(
  first_name: 'John',
  last_name: 'Doe',
  street: 'Bahnhofstrasse',
  house_number: '1',
  zip: 8001,
  city: 'Zürich'
)

# Validate the address
service = Swisspost::AddressService.new
result = service.validate(address: address)

# Check the validation result
puts result.quality.description
# Possible qualities:
# - DOMICILE_CERTIFIED: The address, including the full name of the person, is certified by SwissPost
# - CERTIFIED: The address is certified by the Swiss Post
# - USABLE: Parts of the address have been recognized and the address is considered as reusable
# - FIXED: The address is USABLE, but some minor typos have been corrected
# - UNUSABLE: The system was not able to recognize an acceptable address
# - COMPROMISED: The address may have been modified by a man in the middle

# Get the validated address
validated_address = result.address

Barcode Generation Service

Generate address labels with barcodes for shipping:

# Create sender and recipient addresses
sender = Swisspost::Model::Address.new(
  first_name: 'Alice',
  last_name: 'Smith',
  street: 'Poststrasse',
  house_number: '10',
  zip: 3000,
  city: 'Bern'
)

recipient = Swisspost::Model::Address.new(
  first_name: 'Bob',
  last_name: 'Johnson',
  street: 'Hauptstrasse',
  house_number: '5',
  zip: 4000,
  city: 'Basel'
)

# Create a barcode item with service type and weight
item = Swisspost::Model::BarcodeItem.new(
  service_code: 'PRI',  # Options: ECO, PRI, APOST, BPOST
  weight: 100  # Weight in grams
)

# Generate the barcode label
service = Swisspost::BarcodeService.new
result = service.generate(
  sender: sender,
  recipient: recipient,
  item: item
)

# The result contains the label image and content type
# result.image contains the base64-encoded label image
# result.content_type contains the image format (e.g., 'image/png')

# Save the label to a file
require 'base64'
File.open('shipping_label.png', 'wb') do |file|
  file.write(Base64.decode64(result.image))
end

Price Calculation Service

Calculate shipping prices for different countries and package formats:

service = Swisspost::PriceService.new

# Get available products for shipping
products = service.products(
  country: 'DE',    # ISO country code (e.g., 'DE' for Germany, 'FR' for France)
  format: 'B5',     # Package format: B4, B5, MB, PK, SP, RL, FF
  weight: 500       # Weight in grams
)

# The result contains available shipping products with prices
products.each do |product|
  puts "#{product['name']}: CHF #{product['price']}"
end

Error Handling

All services raise appropriate errors when validation fails or API calls are unsuccessful:

begin
  # Invalid address (ZIP code out of range)
  address = Swisspost::Model::Address.new(
    first_name: 'John',
    last_name: 'Doe',
    street: 'Invalid Street',
    house_number: '999',
    zip: 999,  # Invalid Swiss ZIP code
    city: 'Unknown'
  )
rescue Swisspost::ValidationError => e
  puts "Validation failed: #{e.message}"
end

begin
  service = Swisspost::AddressService.new
  result = service.validate(address: some_address)
rescue HTTPX::HTTPError => e
  puts "API request failed: #{e.message}"
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/swisspost. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Swisspost project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.