Hey there, fellow developer! Ready to dive into the world of Walmart API integration? You're in for a treat. Walmart's API is a powerhouse, offering access to a vast marketplace and opening up endless possibilities for your e-commerce projects. Let's get cracking!
Before we jump in, make sure you've got:
Alright, let's lay the groundwork:
# Create a new Ruby project mkdir walmart_api_integration cd walmart_api_integration # Create a Gemfile echo "source 'https://rubygems.org'" > Gemfile echo "gem 'httparty'" >> Gemfile echo "gem 'dotenv'" >> Gemfile # Install the gems bundle install
Time to get that access token:
require 'httparty' require 'dotenv/load' class WalmartAPI include HTTParty base_uri 'https://marketplace.walmartapis.com' def initialize @options = { headers: { 'WM_SEC.ACCESS_TOKEN' => get_access_token, 'WM_QOS.CORRELATION_ID' => SecureRandom.uuid, 'Accept' => 'application/json' } } end private def get_access_token # Implement token fetching logic here # Don't forget to handle expiration and refreshing! end end
Let's make our first request:
def search_products(query) self.class.get("/v3/items/search?query=#{query}", @options) end
Here are some endpoints you'll likely use:
def get_order(purchase_order_id) self.class.get("/v3/orders/#{purchase_order_id}", @options) end def update_inventory(sku, quantity) self.class.put("/v3/inventory", @options.merge( body: { sku: sku, quantity: quantity }.to_json )) end
Parse that JSON like a pro:
require 'json' def parse_product_data(response) JSON.parse(response.body)['items'].map do |item| { id: item['itemId'], name: item['name'], price: item['salePrice'] } end end
Don't let those errors catch you off guard:
def make_request response = yield handle_response(response) rescue StandardError => e logger.error("API request failed: #{e.message}") raise end def handle_response(response) case response.code when 200..299 response when 401 raise "Unauthorized: #{response.body}" else raise "Request failed: #{response.body}" end end
Play nice with Walmart's servers:
require 'redis' class RateLimiter def initialize(limit, period) @limit = limit @period = period @redis = Redis.new end def throttle(key) current = @redis.get(key).to_i if current >= @limit sleep @period @redis.set(key, 1) else @redis.incr(key) @redis.expire(key, @period) end end end # Usage limiter = RateLimiter.new(5, 1) # 5 requests per second limiter.throttle('walmart_api')
Don't forget to test your integration:
require 'minitest/autorun' require 'webmock/minitest' class WalmartAPITest < Minitest::Test def setup @api = WalmartAPI.new end def test_search_products stub_request(:get, "https://marketplace.walmartapis.com/v3/items/search?query=xbox") .to_return(status: 200, body: '{"items": []}', headers: {}) response = @api.search_products('xbox') assert_equal 200, response.code end end
And there you have it! You're now equipped to build a robust Walmart API integration in Ruby. Remember, this is just the beginning. Keep exploring the API docs, experiment with different endpoints, and most importantly, have fun building awesome e-commerce solutions!
Happy coding, and may your integration be bug-free and your responses lightning-fast! 🚀