Peter
Peter

Reputation: 371

API call via Office scripts in MS Excel WebApp

In the Excel WebApp (Office 365) it is possible to place Office Scripts via the "Automate" tab, which is using the JavaScript-syntax and which could automate excel like a VBA-macro, but for the excel WebApp (Screenshot).

How is it possible to add an API call to an external endpoint (Like a GET request) via this Excel WebApp "Automate" Office Script?
(A scenario would be fetched data from an external API (like weather data) for display in the excel-grid of the excel-webapp).

Screenshot of the excel webapp with office-scripts-code-editor opened

Upvotes: 1

Views: 6198

Answers (3)

iqb0
iqb0

Reputation: 1

just to confirm, post from @kinuasa gives me an error "Office Scripts cannot infer the data type of this variable. Please declare a type for the variable.". Adding type to the output solves helped - "const json: string = await res.json();"

Upvotes: 0

kinuasa
kinuasa

Reputation: 91

Awesome, is there a code-sample available for a POST request as well?

Please refer to the below.

async function main(workbook: ExcelScript.Workbook) {
    const param = {
      method: "POST",
      body: JSON.stringify({
        title: "Test",
        body: "Hello World.",
        userId: 1
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    };
    const res = await fetch("https://jsonplaceholder.typicode.com/posts/", param);
    const json = await res.json();
    console.log(json);
}

Upvotes: 3

Daniel G. Wilson
Daniel G. Wilson

Reputation: 15065

Requests to external APIs / URLs can be achieved with fetch()

Example:

async function main(workbook: ExcelScript.Workbook) {
  const uri = 'https://jsonplaceholder.typicode.com/posts/1';
  const result = await fetch(uri);
  const json = await result.json();
  
  console.log(json);
}

Upvotes: 4

Related Questions