t-s*_*ent 5 curl r oauth oauth-2.0 httr
我正在尝试使用 r 和 httr 访问domain.com.au api。我可以使用 API 密钥来实现此目的,但不能使用 OAuth2
该文档表明:
通过客户端凭证获取访问令牌 使用您的 client_id 和 client_secret 以及您需要的范围列表向https://auth.domain.com.au/v1/connect/token端点发出 POST 请求。请参阅 API 参考,了解每个端点所需的范围列表。尝试使用计划中未包含的范围将导致 400 invalid_scope 错误。该请求必须使用基本身份验证进行身份验证,其中 client_id 和 client_secret 分别对应于用户名和密码。
https://developer.domain.com.au/docs/v2/authentication/oauth/client-credentials-grant
卷曲的实现很简单:
curl -X POST -u 'clientid:secret' -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=client_credentials&scope=api_listings_read%20api_agencies_read' 'https://auth.domain.com.au/v1/connect/token'
Run Code Online (Sandbox Code Playgroud)
它返回令牌而不进行任何重定向。
但是,我无法将其转换为等效的 httr POST 请求来获取令牌。我目前拥有的是:
oep <- oauth_endpoint(base_url = "https://auth.domain.com.au/v1/connect/token",
request = NULL,
access = "access_token" )
myapp <- oauth_app("domain",
key = "client_id_here",
# The secret isn't secrete. A user still has to authenticate when redirected.
secret = "secret_here"
)
# Retrieve the token
token <- oauth2.0_token(oep,
myapp,
scope = "api_listings_read")
Run Code Online (Sandbox Code Playgroud)
这不必要地重定向到一个未知页面,我将其关闭,然后返回到控制台,在控制台中按转义键退出。
我正在审查Converting cURL to httr in R但到目前为止还没有让它工作。
任何帮助将非常感激。
我解决了这个问题。似乎最简单的解决方案是将每个身体中的所有内容都包括在内
r <- POST("https://auth.domain.com.au/v1/connect/token",
config = list(),
body = list(
grant_type="client_credentials",
client_id="myclientid",
client_secret="mysecret",
scope="api_suburbperformance_read"
),
encode = "form"
)
warn_for_status(r)
content(r)
$access_token
[1] "my_requested_token"
$expires_in
[1] 43200
$token_type
[1] "Bearer"
tok <- content(r)$access_token
rg <- GET("https://api.domain.com.au/v2/suburbPerformanceStatistics/NSW/Pyrmont/2009",
add_headers("Content-Type"="application/x-www-form-urlencoded",
Accept="text/plain",
"Authorization"=paste("Bearer", tok)))
warn_for_status(rg)
content(rg)
$header
$header$suburb
[1] "Pyrmont"
$header$state
[1] "NSW"
$header$propertyCategory
[1] "House"
$series
$series$seriesInfo
$series$seriesInfo[[1]]
$series$seriesInfo[[1]]$year
[1] 2020
$series$seriesInfo[[1]]$month
[1] 2
etc. etc.
Run Code Online (Sandbox Code Playgroud)
其中form是包含Content-Type: application/x-www-form-urlencoded在标头中的简写。
我Accept="text/plain"通过转到端点文档https://developer.domain.com.au/docs/v2/apis/pkg_properties_locations/references/suburbperformance_get_bynamedsuburb并按照“尝试一下”说明,找到了应该包含在 get 请求中的内容我可以查看curl命令结构(请注意下面命令的 -H 部分)。
curl -X GET "https://api.domain.com.au/v2/suburbPerformanceStatistics/NSW/Pyrmont/2009?bedrooms=3&startingPeriodRelativeToCurrent=1&totalPeriods=4" -H "accept: text/plain" -H "Authorization: Bearer my_requested_token"
Run Code Online (Sandbox Code Playgroud)
顺便说一句,作为一个使用 的初学者httr,我会评论说,该 api 对于常规或常见用例之外的任何情况似乎都没有特别帮助。它在从用户那里抽象出低级细节方面已经走得太远了。处理像这样的非标准案例的小插图会有所帮助。尽管如此,我承认我的评论可能只是源于不得不花几个小时来弄清楚如何实现一个本来应该是非常简单的过程的挫败感。
我会将其置于未答复状态几天,看看其他人是否可以提出更好的替代方案或提供一些额外的启示。
| 归档时间: |
|
| 查看次数: |
1140 次 |
| 最近记录: |