You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Coinbase RESTClient?PEM文件加载报错问题排查

Coinbase API调用报错:Unable to load PEM file. MalformedFraming

问题背景

已在Coinbase平台注册API密钥,将API密钥及EC私钥存储在.env文件中,配置了requirements.txt依赖并编写了基于FastAPI的服务代码,尝试通过Coinbase RESTClient调用接口获取账户信息。服务器可正常启动,但调用/account接口时出现「Unable to load PEM file. MalformedFraming」错误。


配置与代码详情

1. .env文件内容(测试用密钥,非真实密钥)

COINBASE_API_KEY=3398a3
COINBASE_API_SECRET=-----BEGIN EC PRIVATE KEY-----
EsOY8CRow==
-----END EC PRIVATE KEY-----

2. requirements.txt内容

fastapi
uvicorn[standard]


# for environment variables
python-dotenv


# Coinbase Advanced Trade API client
coinbase-advanced-py

3. 服务端主代码

from fastapi import FastAPI
from app.endpoints import account

from dotenv import load_dotenv
load_dotenv()  # 加载.env文件到环境变量

import logging
logging.basicConfig(
    level=logging.INFO,  # <-- 启用info级日志
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)

app = FastAPI(
    title="crypto-trader",
    description="与Coinbase高级交易API交互的服务",
    version="1.0.0"
)

app.include_router(account.router)

4. 账户端点代码(app/endpoints/account.py)

# app/endpoints/account.py
from fastapi import APIRouter
from app.services.coinbase_client import get_accounts

router = APIRouter()

@router.get("/account", tags=["Account"])
def account_info():
    return get_accounts()

5. Coinbase客户端交互代码(app/services/coinbase_client.py)

# app/services/coinbase_client.py
import logging
from app.core.config import COINBASE_API_KEY, COINBASE_API_SECRET

logger = logging.getLogger(__name__)

try:
    from coinbase.rest import RESTClient
except ImportError as e:
    logger.error("无法从coinbase.rest导入RESTClient")
    logger.exception(e)
    raise

try:
    client = RESTClient(api_key=COINBASE_API_KEY, api_secret=COINBASE_API_SECRET, verbose=True)
except Exception as e:
    logger.error("使用提供的API凭证初始化RESTClient失败")
    logger.exception(e)
    raise

def get_accounts():
    logger.info(f"==================================================COINBASE_API_KEY: {COINBASE_API_KEY}")
    try:
        return client.get_accounts()
    except Exception as e:
        logger.error("从Coinbase API获取账户信息失败")
        logger.exception(e)
        # 选项1:抛出异常让调用方显式处理
        # raise

        # 选项2:返回错误字典(当前选择)
        return {"error": str(e)}

报错详情

服务器可正常启动,但调用/account接口时出现以下错误:

2025-06-12 00:05:57,379 - app.services.coinbase_client - INFO - ==================================================COINBASE_API_KEY: 3398a3
2025-06-12 00:05:57,381 - app.services.coinbase_client - ERROR - 从Coinbase API获取账户信息失败
2025-06-12 00:05:57,381 - app.services.coinbase_client - ERROR - Unable to load PEM file. MalformedFraming
Are you sure you generated your key at https://cloud.coinbase.com/access/api ?
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/coinbase/jwt_generator.py", line 16, in build_jwt
    private_key = serialization.load_pem_private_key(
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: Unable to load PEM file. MalformedFraming

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/workspace/app/services/coinbase_client.py", line 29, in get_accounts
    return client.get_accounts()
           ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/coinbase/rest/accounts.py", line 37, in get_accounts
    return ListAccountsResponse(self.get(endpoint, params=params, **kwargs))
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/coinbase/rest/rest_base.py", line 101, in get
    return self.prepare_and_send_request(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/coinbase/rest/rest_base.py", line 199, in prepare_and_send_request
    headers = self.set_headers(http_method, url_path)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/coinbase/rest/rest_base.py", line 255, in set_headers
    "Authorization": f"Bearer {jwt_generator.build_rest_jwt(uri, self.api_key, self.api_secret)}",
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/coinbase/jwt_generator.py", line 63, in build_rest_jwt
    return build_jwt(key_var, secret_var, uri=uri)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/coinbase/jwt_generator.py", line 21, in build_jwt
    raise Exception(
Exception: Unable to load PEM file. MalformedFraming
Are you sure you generated your key at https://cloud.coinbase.com/access/api ?

解决方案

1. 核对私钥格式

报错根源是PEM格式不合法。你提供的测试私钥只有一行内容,不符合EC私钥的标准结构。真实的Coinbase EC私钥是多行Base64编码内容,包含完整的头部、多行密钥体和尾部。

重新从Coinbase平台复制私钥,确保内容完整,没有遗漏换行或字符。

2. 修正.env文件的多行变量存储

在.env中存储多行私钥时,必须用双引号包裹,避免环境变量解析时丢失换行:

COINBASE_API_KEY=3398a3
COINBASE_API_SECRET="-----BEGIN EC PRIVATE KEY-----
EsOY8CRow==
-----END EC PRIVATE KEY-----"

3. 验证私钥有效性

用OpenSSL命令检查私钥格式是否正确:

openssl ec -in private_key.pem -text -noout

如果命令能正常输出密钥详情,说明格式无误;若报错,重新生成并下载Coinbase私钥。

4. 确认配置加载逻辑

检查app/core/config.py中读取环境变量的代码,确保私钥被完整读取,没有被转义或截断:

import os

COINBASE_API_KEY = os.getenv("COINBASE_API_KEY")
COINBASE_API_SECRET = os.getenv("COINBASE_API_SECRET")

内容的提问来源于stack exchange,提问作者MrLister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 22:07:33