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
requestslibrary automatically sets theContent-Typeheader toapplication/x-www-form-urlencoded(since you passed a string as thedataparameter) - 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
querydirectly as thebodyparameter, just like Python'srequests.posthandles string input. - Content-Type Header: Python's
requestsauto-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, andfromJSON()converts it to an R-native object—equivalent to Python'sjson.loads(r.text).
内容的提问来源于stack exchange,提问作者userJT
相关产品推荐
相关产品推荐

