Nowak
Nowak

Reputation: 145

How do I translate my CLI curl POST api create user call to R httr?

I want to add users to groups on nextcloud via their API.

I succeeded with adding one user (ncuser) to Group1 and Group2 from my CLI, by running this request:

curl -X POST https://adminuser:'admin pass phrase'@cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups -d groupid="Group1" -d groupid="Group2" -H "OCS-APIRequest: true"

With the following response:

<?xml version="1.0"?>
<ocs>
 <meta>
  <status>ok</status>
  <statuscode>100</statuscode>
  <message>OK</message>
  <totalitems></totalitems>
  <itemsperpage></itemsperpage>
 </meta>
 <data/>
</ocs>

I attempted to run the request in Rstudio with this code:

library(curl)
library(httr)

call <- POST("https://adminuser:'admin pass phrase'@cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups",
     body = list(groupid = "Group1", groupid = "Group2"),
     add_headers('OCS-APIRequest' = "true", 'Content-Type' = "application/x-www-form-urlencoded"))

But this isn't successful. I get this response in R:

Response [https://adminuser:'admin pass phrase'@cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups]
  Date: 2020-03-22 15:43
  Status: 401
  Content-Type: application/json; charset=utf-8
  Size: 140 B

Here is the content of my R POST request:

content(call)

$ocs
$ocs$meta
$ocs$meta$status
[1] "failure"

$ocs$meta$statuscode
[1] 997

$ocs$meta$message
[1] "Current user is not logged in"

$ocs$meta$totalitems
[1] ""

$ocs$meta$itemsperpage
[1] ""


$ocs$data
list()

It seems like I wasn't able to login through the POST() url, and need to add adminuser and 'admin pass phrase' in some other way, but i am not sure how.

Also, the nextcloud API documentation states that OCS-APIRequest and the content type needs to be specified in the header, but I am not sure if i did that correctly.

All calls to OCS endpoints require the OCS-APIRequest header to be set to true.

All POST requests require the Content-Type: application/x-www-form-urlencoded header. (Note: Some libraries like cURL set this header automatically, others require setting the header explicitly.)

How should my POST request be written in R so that I can successfully add my nextcloud users to groups?

Any help would be highly appreciated.

Upvotes: 0

Views: 369

Answers (1)

MrFlick
MrFlick

Reputation: 206401

Maybe try

call <- POST("https://cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups",
     body = list(groupid = "Group1", groupid = "Group2"),
     add_headers('OCS-APIRequest' = "true"),
     authenticate("adminuser", "admin pass phrase"),
     encode = "form")

This will make sure POST encode the body properly and will more safely pass the username/password. You can also try adding in verbose() to get more output. It's not going to be easy to help you without some sort of reproducible example we can use for testing.

Upvotes: 2

Related Questions