bradjasper / ImportJSON

Import JSON into Google Sheets, this library adds various ImportJSON functions to your spreadsheet

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Urgent - Time Sensitive | Send POST JSON Body with URL to retrieve data

andrewhenke opened this issue · comments

Hello! I am working on a time-sensitive project for a client that requires sending a POST request with JSON data inside of said request to a URL, and then parsing and inserting the data into the Google Spreadsheet. I have been unfortunately unable to determine a way to do this and was hoping that you would be able to help, can someone tell me what I am missing or what function to use, or how to modify the code so that I can successfully do like so? I would greatly appreciate it! Thank you!

I just ran into this issue as well. I solved it by having the JSON request body data live in its own cell (on a different sheet to avoid overwriting), and then passed that cell as the payload argument in the ImportJSONViaPost spreadsheet function.

Here's how my working formula looks:

=ImportJSONViaPost("https://foo.bar.us-east-1.amazonaws.com/prod/search", Sheet2!A1, "contentType=application/json")

And my Sheet2!A1 cell contains the raw JSON payload: {"queryStr":"foo bar","category":"location","from":0}

If your request is more complex then I recommend taking a look at the following:

I think the underlying issue is that ImportJSON just passes the payload unchanged to the request (i.e. as a string if you're manually typing it out).

I'd imagine you could also solve this by modifying the ImportJSONViaPost function to parse the string into JSON on line 125.

  if (postOptions["contentType"] == "application/json") {
    postOptions["payload"] = JSON.parse(payload);
  }

That would then allow you to pass the JSON payload as a string to the spreadsheet function. (But would then no longer allow you to pass data that's already formatted as JSON).

Bit of a messy way to go about it but it should work if you do want to pass the JSON payload as a string.

Depending on what you're trying to do it may better to just spend the time to add the additional logic to handle payload data that's formatted as either a string or JSON.

Let me try it out, thank you so much!

@jallen92 So how can I include cookies with the POST request, if I can ask?

And as an update, I am trying this out, but I'm encountering the same issue I've been experiencing before - the POST request is sent, but the JSON payload is not being interpreted with it, it is just returning all data that is available from the endpoint instead of what I am requesting from it based on the JSON payload. Any thoughts?

I got it working, just needed to change the content type section from contentType to content-type. Thank you so much for your assistance!