Tạo file .gitignore và thêm .env vào để loại trừ file này khỏi hệ thống quản lý phiên bản.
.env
Trong tất cả ví dụ, chúng ta sẽ sử dụng thư viện requests (đồng bộ). Hãy import nó trước:
import requests
Public endpoints
Đối với các endpoint công khai, bạn chỉ cần gửi một yêu cầu GET.
Không cần API key.
Ví dụ
# https://docs.backpack.exchange/#tag/Markets/operation/get_open_interest
BASE_URL: str = "https://api.backpack.exchange/" # base api url for all endpoints
symbol: str = "SOL_USDC_PERP" # let's specify the symbol
result_url: str = f"{BASE_URL}api/v1/openInterest?symbol={symbol}" # add your argument as a query string. For GET requests you need only query string
from json import JSONDecodeError
response = requests.get(url=result_url) # make a get request
print(f"response status code: {response}")
if response.status_code == 200:
# make your code safe in case you receive unexpected data
try:
print(f"response json: {response.json()}")
open_interest: str = response.json()[0]["openInterest"]
print(f"open interest: {open_interest}")
except JSONDecodeError:
print(f"response text if response isn't json: {response.text}")
else:
...
response status code: <Response [200]>
response json: [{'openInterest': '81420.17', 'symbol': 'SOL_USDC_PERP', 'timestamp': 1743731167028}]
open interest: 81420.17
Nếu bạn có nhiều hơn một tham số (argument), hãy nối chúng bằng ký hiệu &.
Các endpoint riêng tư
Đối với các endpoint riêng tư, chúng ta cần tạo các header đặc biệt và body yêu cầu (đối với các yêu cầu POST).
import base64 # import base64 as "The signature should then be base64 encoded"
from time import time # import time for timestamp
import os # import os – to access environment variables
from cryptography.hazmat.primitives.asymmetric import ed25519 # import ed25519 to create a private key that will sign the message
# from dotenv import load_dotenv, find_dotenv # to create env variables from your .env file
# use this in your code
# load_dotenv(find_dotenv())
# public_key: str = os.getenv("PUBLIC_KEY")
# secret_key: str = os.getenv("SECRET_KEY")
public_key: str = "zDIJj9qneWIY0IYZ5aXoHcNMCm+XDhVcTssiT0HyY0A=" # unsafe!
secret_key: str = "4odxgSUxFrC/zsKWZF4OQwYAgnNu9hnWH3NxWfLAPz4=" # unsafe!
private_key = ed25519.Ed25519PrivateKey.from_private_bytes(
base64.b64decode(secret_key)
)
Hãy lấy địa chỉ nạp tiền.
timestamp = int(time() * 1e3) # Unix time in milliseconds
window: str = "5000" # Time window in milliseconds that the request is valid for. Increase if you have bad connection.
Bây giờ khi đã có X-Timestamp (dấu thời gian), X-Window (khoảng thời gian hợp lệ) và X-API-Key (khóa công khai). hãy tạo X-Signature.
instruction: str = "depositAddressQuery"
sign_str = f"instruction={instruction}"
# This endpoint requires the "blockchain" parameter
params: dict = {
"blockchain": "Solana",
}
# Generic code to generate a valid query string from any parameters
sorted_params_list = []
for key, value in sorted(params.items()):
if isinstance(value, bool): # boolean variables should be lowercase in query strings
value = str(value).lower()
sorted_params_list.append(f"{key}={value}")
sorted_params = "&".join(sorted_params_list)
if sorted_params:
sign_str += "&" + sorted_params
sign_str += f"×tamp={timestamp}&window={window}"
print(sign_str)