You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

展示API返回结果的最简方案及多API切换实现方法

How to Capture Inputs, Call APIs, and Switch Between Them

Hey there! Let's break down exactly how to build this functionality step by step—from capturing user input to displaying API results and switching between different APIs with a dropdown. I'll use VirusTotal's File Report API as the main example, plus a mock blog API to show how to extend it.


Step 1: Basic HTML Structure

First, we'll create the UI elements needed: an input field for your parameter (like a file hash), a dropdown to select the API, a trigger button, and a div to show results.

<div class="api-tool">
  <label for="input-param">Enter Resource (e.g., File Hash):</label>
  <input type="text" id="input-param" placeholder="99017f6eebbac24f351415dd410d522d">
  
  <label for="api-select">Choose API:</label>
  <select id="api-select">
    <option value="virustotal">VirusTotal File Report</option>
    <option value="blog-content">Blog Content Search</option>
  </select>
  
  <button id="fetch-btn">Fetch Results</button>
  
  <div id="result-container" class="result-box"></div>
</div>

Step 2: JavaScript for API Calls & Logic

Next, we'll write the code to handle user input, make API requests, and display results. I'll include comments to explain each part clearly.

// Replace this with your actual VirusTotal API key (get one from their site!)
const VT_API_KEY = "YOUR_VIRUSTOTAL_API_KEY";

// Grab references to our DOM elements
const inputField = document.getElementById('input-param');
const apiSelect = document.getElementById('api-select');
const fetchBtn = document.getElementById('fetch-btn');
const resultContainer = document.getElementById('result-container');

// Add click handler to the fetch button
fetchBtn.addEventListener('click', async () => {
  const userInput = inputField.value.trim();
  
  // Validate input first—don't make empty API calls!
  if (!userInput) {
    resultContainer.innerHTML = "<p>Please enter a valid resource parameter!</p>";
    return;
  }
  
  // Clear old results and show loading state
  resultContainer.innerHTML = "<p>Loading...</p>";
  
  try {
    let response, apiData;
    const selectedApi = apiSelect.value;
    
    // Switch logic to handle different APIs
    switch(selectedApi) {
      case 'virustotal':
        // Call VirusTotal's v2 File Report API (matches your reference link)
        const vtUrl = `https://www.virustotal.com/vtapi/v2/file/report?apikey=${VT_API_KEY}&resource=${userInput}`;
        response = await fetch(vtUrl);
        apiData = await response.json();
        break;
        
      case 'blog-content':
        // Example: Mock blog content API (replace with your real endpoint)
        const blogUrl = `https://api.example.com/blog/posts?query=${userInput}`;
        response = await fetch(blogUrl);
        apiData = await response.json();
        break;
        
      default:
        throw new Error("Selected API isn't supported yet!");
    }
    
    // Display formatted results (using <pre> to make JSON readable)
    resultContainer.innerHTML = `
      <h3>API Response:</h3>
      <pre>${JSON.stringify(apiData, null, 2)}</pre>
    `;
    
  } catch (error) {
    // Handle errors gracefully (network issues, invalid keys, etc.)
    resultContainer.innerHTML = `<p>Oops, something went wrong: ${error.message}</p>`;
  }
});

Step 3: Key Tips & Best Practices

  • API Key Security: Never expose your VirusTotal (or any) API key in frontend code if you're deploying this publicly. Use a backend proxy to forward requests instead—this keeps your keys hidden.
  • Input Validation: For VirusTotal, you can add extra checks to ensure the input is a valid MD5/SHA1/SHA256 hash.
  • Error Handling: The try/catch block catches network errors, invalid responses, or missing inputs so users get clear feedback.
  • Extending to Content Generation APIs: For tools like content generators, most use POST requests (not GET). You'd adjust the fetch call to include a body with your prompt, plus authorization headers (e.g., Authorization: Bearer YOUR_API_KEY).

Optional: Basic Styling

Make the interface look clean with a little CSS:

.api-tool {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  font-family: Arial, sans-serif;
}

label {
  display: block;
  margin: 1rem 0 0.5rem;
  font-weight: bold;
}

input, select, button {
  padding: 0.8rem;
  margin-bottom: 1rem;
  width: 100%;
  max-width: 400px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.result-box {
  margin-top: 2rem;
  padding: 1.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f8f9fa;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 0.9rem;
}

That's it! Start by testing with a valid VirusTotal file hash, then add more APIs to the dropdown as needed. This setup gives you a flexible foundation to expand into blog resources, content generation, or any other API-driven tool you want to build.

内容的提问来源于stack exchange,提问作者jkells

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:15:55