NueForm API 使用标准 HTTP 状态码并返回结构化的 JSON 错误响应。本指南介绍响应格式、所有可能的错误代码以及在代码中处理错误的模式。
响应格式
成功响应
成功的 API 调用返回一个包含 data 字段的 JSON 对象。列表端点还包含一个带分页信息的 meta 字段。
{
"data": {
"id": "clx1abc2d3e4f5g6h7i8j9k0",
"title": "Customer Feedback",
"status": "published",
"created_at": "2026-01-15T09:30:00.000Z"
}
}
包含分页元数据:
{
"data": [
{
"id": "clx1abc2d3e4f5g6h7i8j9k0",
"title": "Customer Feedback"
},
{
"id": "clx2def3g4h5i6j7k8l9m0n1",
"title": "Employee Survey"
}
],
"meta": {
"page": 1,
"per_page": 20,
"total": 150,
"total_pages": 8
}
}
错误响应
错误响应返回一个包含 error 字段的 JSON 对象,其中包含错误 code、人类可读的 message 和 HTTP status 状态码。
{
"error": {
"code": "NOT_FOUND",
"message": "The requested form could not be found.",
"status": 404
}
}
错误代码
下表列出了 API 返回的所有错误代码:
| 代码 | HTTP 状态 | 描述 |
|---|---|---|
BAD_REQUEST | 400 | 请求格式错误、缺少必填字段或包含无效值。 |
UNAUTHORIZED | 401 | 身份验证失败。API 密钥缺失、格式错误、已撤销或已过期。 |
FORBIDDEN | 403 | 已认证的用户无权执行此操作。 |
NOT_FOUND | 404 | 请求的资源不存在或已认证用户无权访问。 |
CONFLICT | 409 | 请求与资源的当前状态冲突(例如,重复条目)。 |
RATE_LIMITED | 429 | 请求过多。详见速率限制。 |
INTERNAL_ERROR | 500 | 服务器发生意外错误。 |
错误响应示例
400 Bad Request
当请求体无效或缺少必填字段时返回。
{
"error": {
"code": "BAD_REQUEST",
"message": "Field 'title' is required.",
"status": 400
}
}
401 Unauthorized
当身份验证因任何原因失败时返回。
{
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid or expired API key.",
"status": 401
}
}
403 Forbidden
当用户已通过身份验证但缺少权限时返回。常见原因包括访问其他用户的资源或使用当前计划不提供的功能。
{
"error": {
"code": "FORBIDDEN",
"message": "API access is not available on your current plan.",
"status": 403
}
}
404 Not Found
当请求的资源不存在时返回。
{
"error": {
"code": "NOT_FOUND",
"message": "The requested form could not be found.",
"status": 404
}
}
409 Conflict
当请求会创建重复项或与现有数据冲突时返回。
{
"error": {
"code": "CONFLICT",
"message": "A form with this slug already exists.",
"status": 409
}
}
429 Rate Limited
当超过速率限制时返回。包含 Retry-After 头。
{
"error": {
"code": "RATE_LIMITED",
"message": "Rate limit exceeded. Please try again later.",
"status": 429
}
}
500 Internal Error
当发生意外服务器错误时返回。如果此问题持续存在,请联系支持团队。
{
"error": {
"code": "INTERNAL_ERROR",
"message": "An internal error occurred.",
"status": 500
}
}
在代码中处理错误
JavaScript
构建一个可复用的 API 客户端,用于检查错误并抛出类型化异常:
class NueFormApiError extends Error {
constructor(code, message, status) {
super(message);
this.name = "NueFormApiError";
this.code = code;
this.status = status;
}
}
async function nueformRequest(path, options = {}) {
const response = await fetch(`https://app.nueform.com/api/v1${path}`, {
...options,
headers: {
"Authorization": `Bearer ${process.env.NUEFORM_API_KEY}`,
"Content-Type": "application/json",
...options.headers,
},
});
const body = await response.json();
if (!response.ok) {
const { code, message, status } = body.error;
throw new NueFormApiError(code, message, status);
}
return body;
}
// 使用示例
async function getForm(formId) {
try {
const { data } = await nueformRequest(`/forms/${formId}`);
return data;
} catch (error) {
if (error instanceof NueFormApiError) {
switch (error.code) {
case "NOT_FOUND":
console.error(`Form ${formId} does not exist.`);
return null;
case "UNAUTHORIZED":
console.error("Check your API key configuration.");
break;
case "RATE_LIMITED":
console.warn("Rate limited. Implement backoff and retry.");
break;
default:
console.error(`API error [${error.code}]: ${error.message}`);
}
}
throw error;
}
}
Python
import os
import requests
class NueFormApiError(Exception):
def __init__(self, code, message, status):
super().__init__(message)
self.code = code
self.status = status
class NueFormClient:
def __init__(self, api_key=None):
self.api_key = api_key or os.environ["NUEFORM_API_KEY"]
self.base_url = "https://app.nueform.com/api/v1"
def request(self, method, path, **kwargs):
url = f"{self.base_url}{path}"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
response = requests.request(method, url, headers=headers, **kwargs)
body = response.json()
if not response.ok:
error = body["error"]
raise NueFormApiError(
error["code"], error["message"], error["status"]
)
return body
# 使用示例
client = NueFormClient()
try:
result = client.request("GET", f"/forms/{form_id}")
form = result["data"]
print(f"Form: {form['title']}")
except NueFormApiError as e:
if e.code == "NOT_FOUND":
print(f"Form {form_id} does not exist.")
elif e.code == "UNAUTHORIZED":
print("Check your API key configuration.")
elif e.code == "RATE_LIMITED":
print("Rate limited. Implement backoff and retry.")
else:
print(f"API error [{e.code}]: {e}")
最佳实践
始终检查 error 字段
不要仅根据响应体的存在就假设请求成功。在处理响应之前,始终检查 error 字段或验证 HTTP 状态码。
使用具体的错误代码进行流程控制
匹配 error.code(如 NOT_FOUND、RATE_LIMITED)而不是 HTTP 状态码。错误代码是稳定的、描述性的,更容易在应用程序逻辑中推理。
记录错误详情
在日志中包含完整的错误响应以便调试。code、message 和 status 组合在一起提供了足够的上下文来诊断大多数问题,无需重现请求。
使用重试处理 5xx 错误
服务器错误(500 Internal Error)通常是暂时性的。对这些响应实施带指数退避的重试逻辑。将重试次数限制在 2--3 次后失败。
不要将错误消息暴露给最终用户
API 错误消息是为开发者设计的,而不是最终用户。在您的应用程序中将 API 错误映射为用户友好的消息。
如果您持续收到 500 Internal Error 响应,请联系支持团队并提供请求详情和时间戳。服务器错误会在我们端记录并调查。