To efficiently get updated orders from the Copper API, you can use updatedSince query parameter. This parameter allows you to filter orders by the time they were last updated.

1

Get the Last Update Time

To avoid downloading all orders every time, track the last time you checked for updates. Store this updated_at of the last fetched order in a safe place, like a database or a file. This tells your system when you last fetched updates

2

Request Updated Orders

Use the updated_at timestamp to ask the Copper API for any orders updated since that time by passing updatedSince query parameter. The API also lets you specify a limit on how many orders to fetch in one request, which helps manage data better.

3

Process the Orders

Go through each order you receive and do what’s needed — like logging details, updating your system, or triggering other processes. Ensure that your operations can handle repeats without causing issues, in case the same order is fetched again.

4

Update the Last Update Time

After dealing with a batch of orders, update your stored updated_at timestamp to the most recent order update time in that batch. This way, your next API request will only fetch newer updates.

5

Handle Pagination Efficiently

To efficiently handle pagination, request one more order than you actually need. For example, if you want to fetch 100 orders, request 101. Use only the first 100 orders for processing. If you receive the 101st order, it indicates there are more orders to fetch. Repeat the process until the number of orders received is less than or equal to the limit you set (100 in this case), which means there are no more updates.

Example

This is not production-ready code. It’s a simple example to help you understand the process.

import hashlib
import hmac
import json
import os
import requests
import time

ApiKey = os.getenv("COPPER_LIVE_API_KEY")
ApiSecret = os.getenv("COPPER_LIVE_API_SECRET")

def copper_api(method, path, body=None):
   timestamp = str(round(time.time() * 1000))

   body_string = json.dumps(body) if body else ""

   signature = hmac.new(
       key=bytes(ApiSecret, 'utf-8'),
       msg=bytes(timestamp + method + path + body_string, 'utf-8'),
       digestmod=hashlib.sha256
   ).hexdigest()

   url = 'https://api.copper.co' + path

   resp = requests.request(method, url, json=body if body else None, headers={
       'Authorization': 'ApiKey ' + ApiKey,
       'X-Signature': signature,
       'X-Timestamp': timestamp,
       'Content-Type': 'application/json'
   })

   print(f"Copper API ~~~> {method} {url} <~~~ {resp.status_code} {resp.reason}")

   if resp.status_code >= 400:
       raise Exception(f"Copper API Error: {resp.status_code} {resp.reason} <~~~ {resp.text}")

   return resp.json()

def get_latest_updated_at():
   # Retrieve the updated_at value from a database or return 0
   return 0

def save_latest_updated_at(updated_at):
   # Store the updated_at value in a database
   pass

def fetch_updated_orders(last_updated_at):
   # fetch all orders from Copper that have been updated since updated_at
   limit = 101

   response = copper_api("GET", f"/platform/orders?orderType=deposit&updatedSince={last_updated_at}&limit={limit}")
   orders = response.get('orders', [])

    if len(orders) > 0:
       for order in orders[:limit-1]:
           # Process each order
           print(f"{order.get('orderId')} - {order.get('updatedAt')}")
           pass

       last_updated_at = orders[-1].get('updatedAt')
       save_latest_updated_at(last_updated_at)

       if len(orders) > limit - 1:
           time.sleep(10)  # Wait 10 seconds before fetching the next batch of orders
           fetch_updated_orders(last_updated_at)

if __name__ == "__main__":
   fetch_updated_orders(get_latest_updated_at())