Back

Step by Step Guide to Building a Shopee API Integration in Python

Aug 11, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of e-commerce integration? Today, we're tackling the Shopee API with Python. This guide will walk you through creating a robust integration that'll have you managing products, orders, and inventory like a pro. Let's get cracking!

Prerequisites

Before we jump in, make sure you've got:

  • Python 3.7+ installed
  • pip for package management
  • A Shopee partner account with API credentials

Quick tip: Set up a virtual environment to keep things tidy. Trust me, your future self will thank you!

Authentication

First things first, let's get you authenticated:

  1. Log into your Shopee partner account and grab your API key and secret.
  2. Now, let's implement the authentication:
import hmac import hashlib import time def sign(secret, payload): return hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest() timestamp = int(time.time()) payload = f"{your_partner_id}{timestamp}" signature = sign(your_partner_key, payload)

Basic API Setup

Let's create a base client to handle our API calls:

import requests class ShopeeClient: BASE_URL = "https://partner.shopeemobile.com/api/v2" def __init__(self, partner_id, partner_key, shop_id): self.partner_id = partner_id self.partner_key = partner_key self.shop_id = shop_id def make_request(self, endpoint, method="GET", params=None, data=None): timestamp = int(time.time()) url = f"{self.BASE_URL}{endpoint}" payload = f"{self.partner_id}{timestamp}{self.shop_id}" signature = sign(self.partner_key, payload) headers = { "Content-Type": "application/json", "Authorization": signature } response = requests.request(method, url, headers=headers, params=params, json=data) return response.json()

Implementing Core Functionalities

Now for the fun part! Let's implement some key features:

Product Management

def get_product(self, item_id): return self.make_request("/product/get_item_base_info", params={"item_id": item_id}) def add_product(self, product_data): return self.make_request("/product/add_item", method="POST", data=product_data)

Order Management

def get_orders(self, time_from, time_to): params = { "time_from": time_from, "time_to": time_to, "page_size": 100 } return self.make_request("/order/get_order_list", params=params) def update_order_status(self, order_sn, status): data = { "order_sn": order_sn, "status": status } return self.make_request("/order/handle_buyer_cancellation", method="POST", data=data)

Inventory Management

def get_stock(self, item_id): return self.make_request("/product/get_item_base_info", params={"item_id": item_id}) def update_stock(self, item_id, stock): data = { "item_id": item_id, "stock": stock } return self.make_request("/product/update_stock", method="POST", data=data)

Error Handling and Rate Limiting

Let's add some resilience to our code:

import time from requests.exceptions import RequestException def make_request_with_retry(self, *args, **kwargs): max_retries = 3 for attempt in range(max_retries): try: response = self.make_request(*args, **kwargs) if response.get("error"): raise RequestException(response["error"]) return response except RequestException as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff

Data Processing and Storage

Here's a quick example of how you might process and store order data:

import sqlite3 def process_orders(self, orders): conn = sqlite3.connect('shopee_orders.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS orders (order_sn TEXT PRIMARY KEY, status TEXT, create_time INTEGER)''') for order in orders: c.execute("INSERT OR REPLACE INTO orders VALUES (?, ?, ?)", (order['order_sn'], order['order_status'], order['create_time'])) conn.commit() conn.close()

Testing and Validation

Don't forget to test your code! Here's a simple unit test example:

import unittest class TestShopeeClient(unittest.TestCase): def setUp(self): self.client = ShopeeClient("partner_id", "partner_key", "shop_id") def test_get_product(self): response = self.client.get_product("1234567") self.assertIn("item", response) self.assertEqual(response["item"]["item_id"], "1234567") if __name__ == '__main__': unittest.main()

Optimization and Best Practices

To take your integration to the next level:

  1. Implement caching for frequently accessed data.
  2. Use asynchronous requests with aiohttp for better performance.
  3. Implement proper logging for easier debugging.

Conclusion

And there you have it! You've just built a solid foundation for a Shopee API integration. Remember, this is just the beginning - there's always room to expand and improve. Keep exploring the Shopee API documentation for more features you can add.

Happy coding, and may your integration be ever scalable!