Manual API Call

How to manually receive and use the Inference API when autoFetch is disabled.

Updated 27 December 2024
apimanualinferencejavascript

Manual API Call

If you set autoFetch = false, you'll need to manually handle the API response.

Receiving the Inference API

Once the user has clicked to Connect their Onairos account and authorized their data, you will receive the Inference API via window.sendMessage:

// Listen for the API URL response
event.data.source === 'content-script'
&&
event.data.type === 'API_URL_RESPONSE'

You will also be given an ACCESS TOKEN which you must use in any API requests from that specific client.

Token Expiration

This is a short-lived token, for usage on your developer registered domain only, and lasts for 1 hour from issue.

Example Implementation

export default async function UseAPIURL(event) {
  if (event.data && event.data.source === 'content-script' && event.data.type === 'API_URL_RESPONSE') {
    const { APIurl, accessToken } = event.data;
    // Fetch Onairos Data from Returned API url
  }
}

useEffect(() => {
  window.addEventListener('message', UseAPIURL);
  return () => {
    window.removeEventListener('message', UseAPIURL);
  };
}, []);

You will also receive the approved choices from the user.

Using the Inference API

The Inference API provides a machine learning model that generates predictions based on the provided data.

Input Format

Send a POST request to the API endpoint with a JSON payload containing entries for prediction:

Field Type Required Description
textStringYesText input for inference
categoryStringYesCategory of the content
img_urlStringNoURL of associated image

Example Input

{
  "Input": {
    "input1": {
      "text": "Example text input 1",
      "category": "Example Category 1",
      "img_url": "http://example.com/image1.jpg"
    },
    "input2": {
      "text": "Example text input 2",
      "category": "Example Category 2",
      "img_url": "http://example.com/image2.jpg"
    }
  }
}

Making the API Call

Include the access token in the Authorization header:

export default async function UseAPIURL(event) {
  if (event.data && event.data.source === 'content-script' && event.data.type === 'API_URL_RESPONSE') {
    const { apiUrl, accessToken } = event.data;
    
    await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + accessToken
      },
      body: JSON.stringify(InputData),
    })
    .then(async (data) => {
      // Process Onairos Data
    })
    .catch(error => console.error(error));
  }
}