0

I need to dynamically make a call to an API using the following format:

 auth_secret <- paste0("Bearer ", secret)

  headers = c(
    `Authorization` = auth_secret,
    `Notion-Version` = '2022-02-22',
    `Content-Type` = 'application/json' )

  res <- httr::PATCH(url = paste0('https://api.notion.com/v1/pages/', id),
                     httr::add_headers(.headers = headers),
                     body = payload,
                     encode = "json")
  d <- httr::content(res)

This payload works:

payload <- "{\"properties\":{\"Project\":{\"relation\":[{\"id\":\"1d148a9e-783d-47a7-b3e8-2d9c34210355\"}]}}}"

But if I want to create it dynamically, using a paste0 (so it is inside of a function), I get some backslashes added before and after:

payload <- paste0('"{\"properties\":{\"',property_name,'\":{\"relation\":[{\"id\":\"',value,'\"}]}}}"')

print(payload) 

"\"{\"properties\":{\"%7CAK%5E\":{\"relation\":[{\"id\":\"8cb9519e72ca4bbe9e0448807acb8e10\"}]}}}\""

I presume this is due to some weird escape character being added but have run out of ideas. I've added two \ and have gotten same issue. Call fails as JSON is not passed correctly. Is there a workaround?

eflores89
  • 339
  • 2
  • 10
  • 27
  • 3
    There are no backslashes being added. There are double quotes being added because you are putting them there. You have double quotes inside the single quotes when you write `paste0('"{`. Just remove the outer single quotes and you should get the result your want. (The backslash is indeed just an escape character signifying that the following character is a literal double quote character) – Allan Cameron Mar 15 '22 at 15:52
  • It would be easier if you created your payload as a list and let `httr` take care of encoding to a JSON string for you. Also to see what strings look like without escaping, be sure to `cat()` their value rather than `print()`. If you print to the console, certain characters as escaped but that's purely a visual change and doesn't reflect what's actually in the string. – MrFlick Mar 15 '22 at 16:09

1 Answers1

0

This is obviously something to do with the fact that paste0 is escaping even the double quotes you do not want to escape.

No doubt someone is aware of the details. However, when I get weird stuff with paste0, I just use sprintf, which seems to work in this case:

property_name = "Projects"
value = "1d148a9e-783d-47a7-b3e8-2d9c34210355"
payload  <- sprintf(
    "{\"properties\":{\"%s\":{\"relation\":[{\"id\":\"%s\"}]}}}",
    property_name, value
)
print(payload)
# [1] "{\"properties\":{\"Projects\":{\"relation\":[{\"id\":\"1d148a9e-783d-47a7-b3e8-2d9c34210355\"}]}}}"
SamR
  • 8,826
  • 3
  • 11
  • 33