Skip to content

Instantly share code, notes, and snippets.

@mculp
Last active June 29, 2024 17:03
Show Gist options
  • Save mculp/58267ae8437163a0da94f1126e566210 to your computer and use it in GitHub Desktop.
Save mculp/58267ae8437163a0da94f1126e566210 to your computer and use it in GitHub Desktop.
quick api wrapper in ruby

How to generate a quick API Wrapper Ruby gem

Generate gem skeleton

$ bundle gem foo-api-wrapper
$ cd foo-api-wrapper

Edit gemspec, add http.rb as dependency

s.add_dependency 'http'

Bundle

$ bundle install

Add a directory structure that matches the API

For example, for the Jupiter Swap API (https://station.jup.ag/docs/apis/swap-api)

I created a jupiter.rb with the base URL

module Jupiter
  class Error < StandardError; end

  BASE_URL = "https://quote-api.jup.ag/v6"
end

I created a quote.rb

module Jupiter
  class Quote
    def self.get(**params)
      HTTP.get(BASE_URL + "/quote", params: params).parse(:json)
    end
  end
end

I created a swap.rb

module Jupiter
  class Swap
    def self.post(**params)
      HTTP.post(BASE_URL + "/swap", json: params).parse(:json)
    end
  end
end

Usage

quote = Jupiter::Quote.get(inputMint: "123", outputMint: "321", amount: "1")

swap = Jupiter::Swap.post(quoteResponse: quote, userPublicKey: "f8a7df871...")

(optional) Next steps

Use the get and post class methods to instantiate the Quote and Swap classes with both your request and response params.

You can decide if you want to use a strict schema or something like Hashie.

@mezbahalam
Copy link

thank you! @mculp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment