Skip to content

Instantly share code, notes, and snippets.

@math-alpha
Created October 16, 2024 16:17
Show Gist options
  • Save math-alpha/5d2445dd31d80edd82e569658008411e to your computer and use it in GitHub Desktop.
Save math-alpha/5d2445dd31d80edd82e569658008411e to your computer and use it in GitHub Desktop.
Using axios to communicate with a Gradio via API
const axios = require('axios');
// Change these two variables accordingly
const GRADIO_URL = "https://0bb459a4e803601c60.gradio.live";
const myText = "Hello world";
// Standalone Gradio API interface for your backend
async function getPrediction(text) {
try {
const apiUrl = `${GRADIO_URL}/gradio_api/call/predict`;
// First API call (POST)
const { data: { event_id } } = await axios.post(apiUrl, { data: [text] }, {
headers: {
'Content-Type': 'application/json'
}
});
// Now that you have event_id, the second API call (GET)
const { data: result } = await axios.get(`${apiUrl}/${event_id}`);
return result;
} catch (error) {
throw ('Error communicating with gradio:' + error);
}
}
// Usage 1 (Promise)
getPrediction(myText)
.then(prediction => {
console.log(prediction);
})
.catch(error => {
console.error(error);
});
// Usage 2 (Async/Await)
async function main() {
try {
let prediction = await getPrediction(myText);
console.log(prediction);
} catch (error) {
console.error(error);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment