Hey there, fellow developer! Ready to dive into the world of Mercado Libre API integration? You're in for a treat. Mercado Libre's API is a powerhouse for e-commerce in Latin America, and mastering it can open up a world of possibilities for your projects. Let's get our hands dirty and build something awesome!
Before we jump in, make sure you've got:
httparty
and oauth2
gems installed (we'll be using these to make our lives easier)First things first, let's get you authenticated:
require 'oauth2' client = OAuth2::Client.new(YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, site: 'https://api.mercadolibre.com') token = client.password.get_token(YOUR_USERNAME, YOUR_PASSWORD)
Boom! You're in. Keep that token safe; we'll need it.
Now that we're authenticated, let's make some requests:
require 'httparty' class MercadoLibreAPI include HTTParty base_uri 'https://api.mercadolibre.com' def initialize(token) @token = token end def get(endpoint) self.class.get(endpoint, headers: { 'Authorization' => "Bearer #{@token}" }) end end api = MercadoLibreAPI.new(token.token) response = api.get('/users/me') puts response.body
Easy peasy! You've just made your first API call.
Let's explore some key endpoints:
response = api.get('/sites/MLB/search?q=iphone')
response = api.get('/items/MLB1234567890')
response = api.get('/orders/123456789')
response = api.get('/users/123456789')
Always be prepared for the unexpected:
def get(endpoint) response = self.class.get(endpoint, headers: { 'Authorization' => "Bearer #{@token}" }) case response.code when 200 response.parsed_response when 429 raise "Rate limit exceeded. Try again later." else raise "Error: #{response.code} - #{response.message}" end end
And remember, play nice with the API. Respect those rate limits!
Once you've got your data, don't forget to parse and store it:
products = JSON.parse(response.body) products.each do |product| # Store in your database Product.create(name: product['title'], price: product['price']) end
Ready to level up? Let's implement webhooks:
post '/webhook' do payload = JSON.parse(request.body.read) # Process the webhook payload status 200 end
Always test your integration:
require 'minitest/autorun' class TestMercadoLibreAPI < Minitest::Test def setup @api = MercadoLibreAPI.new(TOKEN) end def test_get_user response = @api.get('/users/me') assert_equal 200, response.code end end
And there you have it! You've just built a solid Mercado Libre API integration in Ruby. Remember, this is just the beginning. Keep exploring, keep building, and most importantly, keep having fun with it. The e-commerce world is your oyster now. Go make something amazing!