Back

Step by Step Guide to Building a Shippo API Integration in Ruby

Sep 14, 20244 minute read

Introduction

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.

Prerequisites

Before we jump in, make sure you've got:

  • Ruby 2.5+ installed
  • A Shippo account (grab that API key!)
  • Your favorite text editor or IDE

Installation

First things first, let's get the Shippo gem installed:

gem install shippo

Or add it to your Gemfile:

gem 'shippo'

Authentication

Time to authenticate! It's as simple as:

require 'shippo' Shippo::API.token = 'your_api_key_here'

Basic API Requests

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)

Creating a Shipment

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 }] )

Generating Shipping Rates

Let's see what rates we can get:

rates = shipment.rates rates.each do |rate| puts "#{rate.provider} - #{rate.amount} #{rate.currency}" end

Purchasing a Label

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}"

Tracking a Shipment

Keep an eye on that package:

tracking = Shippo::Track.get(transaction.tracking_number, transaction.carrier) puts "Status: #{tracking.tracking_status}"

Error Handling

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

Best Practices

  • Respect rate limits (currently 120 requests per minute)
  • Use webhooks for real-time updates
  • Leverage Shippo's test mode for development

Testing

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!

Conclusion

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!