向 Python 中的 API 发送 PUT 请求。错误 400 错误请求

问题描述 投票:0回答:1

我目前正在致力于实现一个 Python 脚本以将 PUT 请求发送到外部 API。然而,尽管根据 API 文档格式化我的有效负载,我还是收到了“400 Bad Request”错误,其中包含以下详细信息:

{
  "errors": {
    "": [
      "Error converting value \"...\" to type 'System.Collections.Generic.IEnumerable`1[Sma.Sp.GridControlApi.Interfaces.Request.PlantSettings.PlantGridSettingsRequest]'. Path '', line 1, position 3336."
    ],
    "requests": [
      "The requests field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-3711d26de9749eb9b799b1e12771085b-deb81903e5a9837b-00"
}

这是Python代码:

    import json
    import requests
    
    payload = [
  {
    "isDynamicActivePowerLimitEnabled": True,
    "curtailmentTargetPercent": 168,
    "rampSetting": {
      "increasingRampPercentPerSecond": 189,
      "decreasingRampPercentPerSecond": 71
    },
    "timeoutInSeconds": 131,
    "isFallbackEnabled": False,
    "requestType": "ActivePowerDefaultDynamicTargetSettings"
  },
  {
    "fixedLimitPercent": 41,
    "isFixedActivePowerLimitEnabled": True,
    "requestType": "ActivePowerFixedLimitSettings"
  },
  {
    "openLoopSetting": {
      "responseTimeInMilliseconds": 372147
    },
    "underFreqActivePowerDroops": {
      "curvePoint1": {
        "frequencyHz": 36,
        "activePowerPercentChange": 75
      },
      "curvePoint2": {
        "frequencyHz": 187,
        "activePowerPercentChange": 18
      },
      "curvePoint3": {
        "frequencyHz": 46,
        "activePowerPercentChange": 30
      }
    },
    "overFreqActivePowerDroops": {
      "curvePoint1": {
        "frequencyHz": 55,
        "activePowerPercentChange": 20
      },
      "curvePoint2": {
        "frequencyHz": 54,
        "activePowerPercentChange": 161
      },
      "curvePoint3": {
        "frequencyHz": 225,
        "activePowerPercentChange": 87
      }
    },
    "isFreqWattActive": False,
    "requestType": "ActivePowerFreqWattSettings"
  },
  {
    "operationRampPercentPerSecond": 125,
    "connectionRampPercentPerSecond": 79,
    "requestType": "ActivePowerRampSettings"
  },
  {
    "openLoopSettings": {
      "responseTimeInMilliseconds": 393587
    },
    "crvRampSettings": {
      "increasingRampPercentPerSecond": 119,
      "decreasingRampPercentPerSecond": 152
    },
    "voltWattCurvePoints": [
      {
        "nominalVoltagePercentage": 248,
        "activePowerPercentage": 207
      },
      {
        "nominalVoltagePercentage": 42,
        "activePowerPercentage": 115
      },
      {
        "nominalVoltagePercentage": 204,
        "activePowerPercentage": 255
      }
    ],
    "isVoltWattEnabled": True,
    "requestType": "ActivePowerVoltWattCurveSettings"
  },
  {
    "isEnergized": False,
    "requestType": "EnergizeSettings"
  },
  {
    "highFrequencyFrtSettings": {
      "threshold1NominalFrequencyPercent": 129,
      "threshold1DurationMillis": 246,
      "threshold2NominalFrequencyPercent": 154,
      "threshold2DurationMillis": 158
    },
    "lowFrequencyFrtSettings": {
      "threshold1NominalFrequencyPercent": 11,
      "threshold1DurationMillis": 149,
      "threshold2NominalFrequencyPercent": 185,
      "threshold2DurationMillis": 148
    },
    "requestType": "FrequencyFaultRideThroughSettings"
  },
  {
    "openLoopSetting": {
      "responseTimeInMilliseconds": 453635
    },
    "rampSetting": {
      "increasingRampPercentPerSecond": 56,
      "decreasingRampPercentPerSecond": 193
    },
    "voltVarCurvePoints": [
      {
        "isOverExcited": True,
        "nominalVoltagePercentage": 221,
        "reactivePowerPercentage": 31
      },
      {
        "isOverExcited": False,
        "nominalVoltagePercentage": 162,
        "reactivePowerPercentage": 169
      },
      {
        "isOverExcited": True,
        "nominalVoltagePercentage": 123,
        "reactivePowerPercentage": 15
      }
    ],
    "isVoltVarEnabled": False,
    "requestType": "ReactivePowerVoltVarCurveSettings"
  },
  {
    "highVoltageFrtSettings": {
      "threshold1NominalVoltagePercent": 112,
      "threshold1DurationMillis": 21,
      "threshold2NominalVoltagePercent": 165,
      "threshold2DurationMillis": 218,
      "threshold3NominalVoltagePercent": 28,
      "threshold3DurationMillis": 117
    },
    "lowVoltageFrtSettings": {
      "threshold1NominalVoltagePercent": 85,
      "threshold1DurationMillis": 242,
      "threshold2NominalVoltagePercent": 124,
      "threshold2DurationMillis": 155,
      "threshold3NominalVoltagePercent": 177,
      "threshold3DurationMillis": 22
    },
    "requestType": "VoltageFaultRideThroughSettings"
  }
]
    
    # Convert to JSON format
    json_payload = json.dumps({"requests": payload})
    

    url = "https://****/endpoint"
  
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer <your_token_here>"  # Add if necessary
    }
    
    response = requests.put(url, data=json_payload, headers=headers)
    print(response.status_code)
    print(response.text)

我尝试正确格式化我的有效负载并根据 API 的要求设置标头。可能是什么导致了这个问题,我该如何解决它?

python json put
1个回答
0
投票

400 Bad Request 错误表示服务器无法理解该请求。导致此错误的原因可能有多种,例如请求参数不正确、标头丢失或请求正文格式错误。

这是使用 Python 中的

requests
库发送 PUT 请求的基本示例:

import requests

url = "https://example.com/api/resource"
data = {"key": "value"}

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",  # Include any required headers
}

response = requests.put(url, json=data, headers=headers)

print(f"Status code: {response.status_code}")
print(f"Response content: {response.text}")

确保将占位符值替换为您的实际 API 端点、数据和标头。

如果您仍然收到 400 错误,请考虑以下事项:

  1. 检查 API 文档: 确保您使用 API 文档中指定的正确端点、标头和请求参数。

  2. 验证授权:如果您的 API 需要身份验证,请确保您在

    Authorization
    标头中提供正确的凭据或访问令牌。

  3. 请求有效负载格式:确保您在请求正文中发送的数据(示例中的

    json=data
    )遵循预期格式。

  4. 标头: 确认您正在设置任何必需的标头,例如

    Content-Type

  5. 调试:打印响应的内容(

    response.text
    )以查看服务器是否提供有关错误的更多详细信息。

如果您可以提供有关您的请求和收到的任何错误消息的更多详细信息,我也许可以为您提供进一步帮助。

© www.soinside.com 2019 - 2024. All rights reserved.