Hey there, fellow developer! Ready to dive into the world of Mercado Libre's API? Whether you're looking to build a price comparison tool or create a seamless shopping experience, this guide will walk you through integrating Mercado Libre's API into your Python project. Let's get started!
Before we jump in, make sure you've got:
pip
for package managementYou'll also need to install a few packages:
pip install requests
First things first, let's get you authenticated. Mercado Libre uses OAuth 2.0, so you'll need to get an access token.
import requests client_id = 'YOUR_CLIENT_ID' client_secret = 'YOUR_CLIENT_SECRET' redirect_uri = 'YOUR_REDIRECT_URI' # Get the access token response = requests.post('https://api.mercadolibre.com/oauth/token', data={ 'grant_type': 'authorization_code', 'client_id': client_id, 'client_secret': client_secret, 'code': 'THE_CODE', 'redirect_uri': redirect_uri }) access_token = response.json()['access_token']
Pro tip: Store your access token securely and implement a refresh mechanism to keep it valid.
Now that you're authenticated, let's make your first API call:
headers = {'Authorization': f'Bearer {access_token}'} response = requests.get('https://api.mercadolibre.com/sites/MLB/categories', headers=headers) if response.status_code == 200: categories = response.json() print(categories) else: print(f"Error: {response.status_code}")
Mercado Libre's API is vast, but here are some endpoints you'll likely use often:
/items/{item_id}
/sites/{site_id}/categories
/users/{user_id}
/orders/{order_id}
Let's implement a product search:
def search_products(query, limit=50): url = f'https://api.mercadolibre.com/sites/MLB/search?q={query}&limit={limit}' response = requests.get(url, headers=headers) return response.json()['results'] products = search_products('smartphone') for product in products: print(f"{product['title']} - {product['price']}")
Always handle errors gracefully and respect rate limits:
def make_api_call(url): response = requests.get(url, headers=headers) if response.status_code == 429: print("Rate limit exceeded. Waiting before retrying...") time.sleep(60) return make_api_call(url) response.raise_for_status() return response.json()
Parse JSON responses and consider storing data for faster access:
import json def save_to_file(data, filename): with open(filename, 'w') as f: json.dump(data, f) def load_from_file(filename): with open(filename, 'r') as f: return json.load(f) # Usage save_to_file(products, 'products.json') loaded_products = load_from_file('products.json')
Implement pagination to handle large result sets:
def get_all_results(url): results = [] while url: response = make_api_call(url) results.extend(response['results']) url = response.get('paging', {}).get('next') return results
Always test your API calls:
import unittest class TestMercadoLibreAPI(unittest.TestCase): def test_search_products(self): products = search_products('laptop') self.assertGreater(len(products), 0) self.assertIn('title', products[0]) if __name__ == '__main__': unittest.main()
Congratulations! You've just built a solid foundation for your Mercado Libre API integration. Remember to always refer to the official API documentation for the most up-to-date information. Happy coding, and may your API calls always return 200 OK!