How to Authenticate with AliExpress's API using Python
In this tutorial, we are going to connect an application to AliExpress using Python.
This series covers the buyer / dropshipper API family. You will need an AliExpress developer account, an app approved for the APIs you want to call, and authorization from the account whose data you are accessing. Seller catalog APIs and affiliate APIs have different permissions and methods. An app key by itself does not grant access to an account's orders.
Before we write the code
Open the AliExpress app console, sign in to your developer account, and create your own application. Register a callback URL that you control, such as https://your-app.example.com/oauth/aliexpress, and request the API permissions needed for your integration. Copy your app key and app secret into your local environment. Do not copy credentials or callback URLs from someone else's application.
The callback URL in the authorization request must match the one registered for your app. For development, use a callback your app configuration accepts. An authorization code may appear in the callback URL even if your local callback handler is not running, but a deployed integration needs a real handler.
The flow has three steps: send the account owner to AliExpress, receive the authorization code at your callback, and exchange that code on your server. The official authorization guide describes this code-for-token flow. App approval and the type of account you can authorize depend on your app category, so check the permissions displayed for your own app.
Build an authorization URL with these parameters, URL-encoding each value:
https://api-sg.aliexpress.com/oauth/authorize
?response_type=code
&client_id=YOUR_APP_KEY
&redirect_uri=YOUR_REGISTERED_CALLBACK_URL
&state=YOUR_RANDOM_SINGLE_USE_STATE
Put that on one line before opening it. Generate a cryptographically random state, store it in the user's server-side session with a short expiry, and compare it with the callback's state before accepting the code. Bind the callback to the user who started authorization and consume the state once. Do not accept a code from an arbitrary callback URL. These scripts start after that validation; they are not a complete web callback handler.
AliExpress returns a short-lived code. Exchange it promptly and use a fresh code if it expires or has already been consumed. Keep the full callback URL out of logs, analytics, and screenshots because it contains that code.
Python setup
Use Python 3.10 or later. Create a directory for the example and save the helper below as client.py. Save the operation alongside it. Everything uses the Python standard library, so there is no SDK or pip package to install.
Sign the request
We will use https://api-sg.aliexpress.com/rest for token endpoints and https://api-sg.aliexpress.com/sync for these dropshipping calls. The helper signs requests using HMAC-SHA256 with an uppercase hexadecimal digest:
- Leave
signout of the input and omit empty values. - Sort parameter names in ASCII order.
- Concatenate each name and its unencoded value without separators.
- For token endpoints, prefix
/auth/token/createor/auth/token/refresh. For these/synccalls, use an empty prefix; the method name is already a signed parameter. - Sign the UTF-8 bytes with the app secret, then form-encode the parameters for transport.
We use a millisecond Unix timestamp and send the access token as session for /sync. Do not change the JSON serialization or any other parameter after computing the signature.
AliExpress also publishes older TOP gateway examples with different timestamps, parameters, and signing algorithms. Use the gateway and protocol enabled for your app; do not combine a TOP example with this Singapore-gateway helper. Start with the AliExpress API directory and the individual method page for your app. Confirm that your approved app has permission to call each method before running the examples.
The helper gives each request a timeout, checks HTTP status, and rejects the top-level error_response envelope. API errors can arrive with HTTP 200, so the operation also checks its method-specific result. Error output omits raw bodies because they can contain tokens or personal data.
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
def required(name):
value = os.environ.get(name, "")
if not value:
raise RuntimeError(f"Set {name}")
return value
def signature(params, path, secret):
message = path + "".join(
key + params[key] for key in sorted(params)
if key != "sign" and params[key] != ""
)
return hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest().upper()
def call(endpoint, path, business):
params = {
"app_key": required("ALIEXPRESS_APP_KEY"),
"sign_method": "sha256",
"timestamp": str(time.time_ns() // 1_000_000),
**business,
}
params["sign"] = signature(params, path, required("ALIEXPRESS_APP_SECRET"))
body = urllib.parse.urlencode(params).encode()
request = urllib.request.Request(endpoint, data=body, headers={
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
})
try:
with urllib.request.urlopen(request, timeout=20) as response:
data = json.load(response)
except urllib.error.HTTPError as error:
raise RuntimeError(f"AliExpress HTTP {error.code}; response omitted") from None
except (urllib.error.URLError, TimeoutError):
raise RuntimeError("AliExpress connection failed; details omitted") from None
if not isinstance(data, dict):
raise RuntimeError("Unexpected AliExpress response")
if "error_response" in data:
# Error messages can echo request values. Keep the raw body private.
raise RuntimeError("AliExpress rejected the request; inspect securely")
return data
def sync(method, params):
return call("https://api-sg.aliexpress.com/sync", "", {
"method": method,
"session": required("ALIEXPRESS_ACCESS_TOKEN"),
**params,
})
def save_private(filename, data):
# Create without overwriting an existing file. Run with umask 077 as well.
with open(filename, "x", encoding="utf-8", opener=lambda p, f: os.open(p, f, 0o600)) as file:
json.dump(data, file, indent=2)
file.write("\n")
The private-file helper creates a new file and refuses to overwrite an existing one. For repeated runs, choose a new output path for tokens, or move the previous snapshot to private storage before running a sync again. File permissions are a POSIX safeguard; use your operating system's access controls on Windows.
Exchange the code
Save this as authenticate.py:
import os
from client import call, required, save_private
operation = os.environ.get("ALIEXPRESS_AUTH_OPERATION", "create")
if operation not in ("create", "refresh"):
raise RuntimeError("Use create or refresh")
path = "/auth/token/" + operation
field = "code" if operation == "create" else "refresh_token"
value = required("ALIEXPRESS_CODE" if operation == "create" else "ALIEXPRESS_REFRESH_TOKEN")
tokens = call("https://api-sg.aliexpress.com/rest" + path, path, {field: value})
if str(tokens.get("code", "0")) != "0" or not tokens.get("access_token"):
raise RuntimeError("Token exchange failed; response omitted")
save_private(required("ALIEXPRESS_TOKEN_FILE"), tokens)
print("Token saved privately. expires_in:", tokens.get("expires_in"))
Run the example
Set the environment variables locally using your secret manager or shell. The values below are placeholders. Do not commit your .env file, token file, or downloaded account data. umask 077 makes newly created files private on a POSIX system.
umask 077
export ALIEXPRESS_APP_KEY='your-app-key'
export ALIEXPRESS_APP_SECRET='your-app-secret'
export ALIEXPRESS_CODE='code-from-your-validated-callback'
export ALIEXPRESS_TOKEN_FILE='./aliexpress-tokens.json'
python3 authenticate.py
A successful run saves the complete token response privately and prints only its expires_in value. Load access_token into your backend's credential store and use it as session on the dropshipping calls. Keep the returned refresh token and all expiry fields with the same authorization record. Avoid printing the file to a terminal while recording a tutorial.
Refresh the authorization
Use the same script with a refresh token from your private credential store:
export ALIEXPRESS_AUTH_OPERATION='refresh'
export ALIEXPRESS_REFRESH_TOKEN='your-current-refresh-token'
export ALIEXPRESS_TOKEN_FILE='./aliexpress-tokens-refreshed.json'
python3 authenticate.py
The new output filename matters because the example refuses to overwrite the original file. In your application, atomically replace the stored access token, refresh token, and expiry metadata after a successful refresh. A refresh failure should not erase the previous record. Use a lock or version check so two workers cannot race while refreshing one authorization.
Use the lifetimes returned for your app instead of assuming every token lasts a fixed number of hours. If refresh is unavailable or expired, send the user through authorization again. The app secret signs the request; it is never sent as an ordinary request parameter.
Common problems
For a callback mismatch, compare your registered callback and redirect_uri exactly. For a signature error, check the token path prefix, parameter sorting, UTF-8 bytes, and your system clock. A code that has expired or already been used needs a new authorization flow. A permission error needs a check of the app's grants and the authorizing account; repeating the same request will not add permissions.
A production integration needs a callback handler with state validation, encrypted token storage, and per-account authorization records. The CLI exchange is a way to understand and test that backend step.
Local test result
This screenshot shows an offline fixture run of the Python example. The transport returns synthetic data; it is not evidence of a successful live AliExpress call. Only the summary is displayed, so no account address, token, or tracking number is exposed.

Download the example
The two files are client.py and authenticate.py. Save them together. These are small educational scripts; add schema validation, protected credential storage, and your persistence layer before using them as a background integration.