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

Python的requests.post()在R中的等效实现及参数处理咨询

Convert Python requests.post Call to R Equivalent

Let's break down exactly what your Python code is doing first, then map that to R's standard tools for HTTP requests:

What the Python Code Does

Your snippet sends a POST request to the NDAR API with these key behaviors:

  • The request body is the raw string "asthma"
  • The requests library automatically sets the Content-Type header to application/x-www-form-urlencoded (since you passed a string as the data parameter)
  • Finally, it parses the JSON response into a native Python data structure.

R Implementation Using httr and jsonlite

We'll use httr (the go-to R package for HTTP calls) and jsonlite (for parsing JSON responses) to replicate this behavior exactly:

# Load required libraries
library(httr)
library(jsonlite)

# Define your search query
query <- "asthma"

# Send the POST request (matching Python's behavior)
response <- POST(
  url = "https://ndar.nih.gov/api/search/nda_sw_removal/collection/full",
  body = query,
  content_type("application/x-www-form-urlencoded")  # Match requests' default header
)

# Parse the JSON response into an R object (list/data frame)
collections <- fromJSON(content(response, "text"))

# View the result
collections

Critical Matching Details

  • Request Body: We pass the raw string query directly as the body parameter, just like Python's requests.post handles string input.
  • Content-Type Header: Python's requests auto-sets this header for string data, so we explicitly define it in R to ensure the API receives the request in the expected format.
  • Response Parsing: content(response, "text") fetches the raw response text, and fromJSON() converts it to an R-native object—equivalent to Python's json.loads(r.text).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:27