Hey there, fellow developer! Ready to supercharge your shipping game with Shippo? Let's dive into building a robust Shippo API integration in Ruby. Shippo's API is a powerhouse for all things shipping, and we're about to harness that power in our Ruby application.
Before we jump in, make sure you've got:
First things first, let's get the Shippo gem installed:
gem install shippo
Or add it to your Gemfile:
gem 'shippo'
Time to authenticate! It's as simple as:
require 'shippo' Shippo::API.token = 'your_api_key_here'
Let's start with something simple - creating and validating an address:
address = Shippo::Address.create( name: 'Mr Hippo', company: 'Shippo', street1: '215 Clayton St.', city: 'San Francisco', state: 'CA', zip: '94117', country: 'US' ) validated_address = Shippo::Address.validate(address.object_id)
Now for the fun part - creating a shipment:
shipment = Shippo::Shipment.create( address_from: address, address_to: another_address, parcels: [{ length: 5, width: 5, height: 5, distance_unit: :in, weight: 2, mass_unit: :lb }] )
Let's see what rates we can get:
rates = shipment.rates rates.each do |rate| puts "#{rate.provider} - #{rate.amount} #{rate.currency}" end
Found a rate you like? Let's buy a label:
transaction = Shippo::Transaction.create( rate: rates.first.object_id, label_file_type: "PDF", async: false ) puts "Label URL: #{transaction.label_url}"
Keep an eye on that package:
tracking = Shippo::Track.get(transaction.tracking_number, transaction.carrier) puts "Status: #{tracking.tracking_status}"
Always be prepared! Wrap your API calls in error handling:
begin # Your Shippo API call here rescue Shippo::Exceptions::APIError => e puts "Oops! #{e.message}" end
Speaking of test mode, here's how to use it:
Shippo::API.token = 'shippo_test_your_test_key_here'
And don't forget to write those unit tests!
And there you have it! You're now equipped to integrate Shippo into your Ruby application like a pro. Remember, this is just scratching the surface - Shippo's API has a ton more features to explore. Happy shipping!