Search code examples
rjsonposthttr

Formatting POST body with httr in r


I am trying to change a contact property value in hubspot.

documentation: https://developers.hubspot.com/docs/methods/contacts/update_contact

This item lives in a series of data frames that are encoded in JSON(see GET request below)

I have tried a couple of formats

1) following back the GET requests format

library(httr)
library(jsonlite)
    URL <- paste0('https://api.hubapi.com/contacts/v1/contact/vid/',VID,'/profile?hapikey=',hapikey, sep = "")
    GURL <- GET(url = URL)

Contact <- content(URL, as = "text")
Contact <- fromJSON(Contact)

Contact$properties$needs_statements$value
#returns
[1] "Yes"

#so then working backwards in the POST request:
body <- toJSON('No', content$properties$property$needs_statements$value)

#alternatively
body <- list('No', content$properties$property$needs_statements$value)

#alternatively 
body <- ('No', content$properties$property$needs_statements$value)

#Post Request
POST( url = URL, body = body, encode = "json")

2) trying to follow the python format in the documentation

library(httr)

body <- '{
  "properties": [
    {
      "property": "needs_statements",
      "value": "No"]}
}'

#alternatively
body <- toJSON('{
  "properties": [
    {
      "property": "needs_statements",
      "value": "No"
      }
     ]
    }')

#Post Request
POST( url = URL, body = body, encode = "json")

I have also tried encode = "raw" encode = "form"

These are all pulling back code 400 which indicates an error in the request body.

Shooting for 204.

I'm not including headers or cookies or anything else. I have also had a hard time finding any info on this.

Any help is very appreciated.


Solution

  • okay, so after eating some food and pondering, a quick google produced this: https://cran.r-project.org/web/packages/jsonlite/vignettes/json-aaquickstart.html

    with the test available to do this:

    fromJSON('[{"name":"Erik", "age":43}, {"name":"Anna", "age":32}]')

    Which prints a data frame.

     name age
    1 Erik  43
    2 Anna  32
    

    the tricky part for me came in needing to get the same structure that the original GET request was in.

    (I was trying to build data frames of data frames and it wasn't going well)

    then I thought back to the above test and figured I could do the same test on the JSON. Which I did, and created an element.

    x <- fromJSON('{
      "properties": [
        {
          "property": "needs_statements",
          "value": "No"
        }
        ]
    }')
    

    and boom: 204