首页 > 解决方案 > R POST() 状态 422 错误(msg 'value is not a valid list')

问题描述

我无法在 R 中使用 POST() API。我执行了以下操作:

data  <- list(request_data_type = "expression",
  request_cancer_type = "all",
  request_genes = c("BRCA1", "PALB2", "SRY", "TP53", "NOTCH1"),
  request_models = c("CTG-0009", "CTG-0011", "CTG-0012"),
  request_dataset = "PDX",
  request_key = "XXX",
  request_client = 99,
  request_user = 99,
  request_mode = 'true') 

request  <-  POST(url = 'https://example.com/workstation', 
                  body = data)
request

消息是

Response [https://example.com/workstation]
  Date: 2021-10-11 15:33
  Status: 422
  Content-Type: application/json
  Size: 116 B

我无法获得状态 200。

使用 Python 提取数据没有问题:

import requests
import pandas as pd

data = {
  "request_data_type": "expression",
  "request_cancer_type": ["all"],
  "request_genes": ["BRCA1", "PALB2", "SRY", "TP53", "NOTCH1"],
  "request_models": ["CTG-0009", "CTG-0011", "CTG-0012"],
  "request_dataset": "PDX",
  "request_key": "XXX",
  "request_client": 99,
  "request_user": 99,
  "request_mode": 'true'
}
response = requests.post('https://example.com/workstation', json=data) # this saves a .json file in the directory

df = pd.read_json('../<file_name>.json')
df.head(2)

这给出了预期的结果:[“this dataframe”]

标签: rapi

解决方案


在调试这样的东西时,https://httpreq.com/是一个有用的网页。您可以将两个请求都发送到那里的端点并比较结果。

您似乎已经从encode='json'R 代码中删除了部分内容。这很重要,因为您通过 python 脚本中的 json 发送数据。唯一的其他区别是,您似乎明确地将“request_cancer_type”值“装箱”为数组,而不是 python 代码中的简单字符串值。您可以通过将值包装在 R 中来做到这一点list()。这会为我产生与 python 代码相同的请求:

data  <- list(request_data_type = "expression",
              request_cancer_type = list("all"),
              request_genes = c("BRCA1", "PALB2", "SRY", "TP53", "NOTCH1"),
              request_models = c("CTG-0009", "CTG-0011", "CTG-0012"),
              request_dataset = "PDX",
              request_key = "XXX",
              request_client = 99,
              request_user = 99,
              request_mode = 'true') 

request  <-  POST(url = 'https://example.com/workstation', 
                  body = data, encode='json')

推荐阅读