Hey there, fellow developer! Ready to dive into the world of PrestaShop API integration? You're in for a treat. PrestaShop's API is a powerful tool that lets you interact with your e-commerce store programmatically. In this guide, we'll walk through building a solid integration using Python. Let's get cracking!
Before we jump in, make sure you've got:
If you're all set, let's move on to the fun stuff!
First things first, let's get our environment ready:
pip install requests
That's it! We'll be using the requests
library to handle our HTTP calls. Simple, right?
Now, let's create a basic connection class:
import requests class PrestaShopAPI: def __init__(self, url, key): self.url = url self.key = key self.auth = (key, '') def get(self, resource, resource_id=None): endpoint = f"{self.url}/api/{resource}" if resource_id: endpoint += f"/{resource_id}" response = requests.get(endpoint, auth=self.auth) return response.json()
This class will handle our authentication and provide a basic GET method. Easy peasy!
Let's expand our class to handle all CRUD operations:
class PrestaShopAPI: # ... previous code ... def create(self, resource, data): endpoint = f"{self.url}/api/{resource}" response = requests.post(endpoint, auth=self.auth, json=data) return response.json() def update(self, resource, resource_id, data): endpoint = f"{self.url}/api/{resource}/{resource_id}" response = requests.put(endpoint, auth=self.auth, json=data) return response.json() def delete(self, resource, resource_id): endpoint = f"{self.url}/api/{resource}/{resource_id}" response = requests.delete(endpoint, auth=self.auth) return response.status_code
Now we're cooking with gas! We've got full CRUD capabilities.
Let's create some methods for common resources:
class PrestaShopAPI: # ... previous code ... def get_products(self): return self.get('products') def get_categories(self): return self.get('categories') def create_customer(self, customer_data): return self.create('customers', customer_data) def update_order(self, order_id, order_data): return self.update('orders', order_id, order_data)
These methods make working with specific resources a breeze!
Always expect the unexpected. Let's add some error handling:
class PrestaShopAPI: # ... previous code ... def _handle_response(self, response): if response.status_code == 200: return response.json() elif response.status_code == 404: raise Exception("Resource not found") elif response.status_code == 401: raise Exception("Authentication failed") else: raise Exception(f"API request failed: {response.text}") def get(self, resource, resource_id=None): # ... previous code ... return self._handle_response(response) # Apply _handle_response to other methods as well
This will make debugging much easier when things go sideways.
PrestaShop's API supports pagination and filtering. Let's use them:
class PrestaShopAPI: # ... previous code ... def get_products(self, limit=50, offset=0, **filters): params = { 'limit': limit, 'offset': offset, **filters } return self.get('products', params=params)
Now you can easily paginate and filter your requests. Neat, huh?
Let's put it all together with a simple product sync example:
api = PrestaShopAPI('https://your-store.com', 'YOUR_API_KEY') def sync_products(): products = api.get_products(limit=100, active=1) for product in products: # Sync logic here print(f"Syncing product: {product['name']}") sync_products()
Don't forget to test your integration! Here's a simple unit test:
import unittest from unittest.mock import patch from your_module import PrestaShopAPI class TestPrestaShopAPI(unittest.TestCase): @patch('requests.get') def test_get_products(self, mock_get): mock_get.return_value.json.return_value = {'products': []} api = PrestaShopAPI('https://test.com', 'test_key') result = api.get_products() self.assertEqual(result, {'products': []}) if __name__ == '__main__': unittest.main()
Remember to:
And there you have it! You've just built a robust PrestaShop API integration in Python. From here, you can expand on this foundation to create more complex integrations tailored to your specific needs.
Remember, the PrestaShop API is vast and powerful. Don't be afraid to explore and experiment. Happy coding!