EngineeringBeginner
How to Call an API Using JavaScript: Fetch, Async/Await, and Axios
Direct Answer & Overview
A complete developer tutorial showing how to make GET and POST requests in modern JavaScript using the native Fetch API, async/await, error handling, and Axios in browser and Node.js environments.
1.Calling APIs with the Native Fetch API & Async/Await
Modern JavaScript natively includes `fetch()`, which returns a Promise. Combining `fetch()` with `async/await` syntax allows developers to write asynchronous network code that reads sequentially without nested callback hell.
2.Handling POST Payloads, Headers, and Authentication
When calling authenticated endpoints, you must specify the HTTP method, stringify your data object into JSON, and attach the `Authorization` and `Content-Type` headers.
3.Crucial Gotcha: Fetch Does Not Reject on HTTP 400 or 500
A major pitfall in JavaScript is that `fetch()` only rejects its Promise on network failure (DNS errors or offline). It does NOT reject on HTTP 404, 401, or 500. Developers must manually check `if (!response.ok)` to intercept error responses properly.
Robust Production JavaScript Fetch Function with Error Handlingjavascript
async function generateAIChatCompletion(userPrompt) {
try {
const response = await fetch("https://api.apihundred.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer your_api_key_here"
},
body: JSON.stringify({
model: "gemini-3.8-flash",
messages: [{ role: "user", content: userPrompt }]
})
});
// Check if HTTP status is outside 200-299 range
if (!response.ok) {
const errorDetails = await response.json();
throw new Error(`API Error (${response.status}): ${errorDetails.message || response.statusText}`);
}
const data = await response.json();
return data.choices[0].message.content;
} catch (error) {
console.error("Network or API failure:", error);
throw error;
}
}Frequently Asked Questions
Should I use Axios or native Fetch in 2026?
Native Fetch is built into all modern browsers and Node.js 18+, making external libraries like Axios unnecessary for most standard projects.
How do I handle CORS errors when calling an API from the browser?
CORS prevents browsers from calling third-party APIs directly. Call the API from a backend server or route handler instead of directly in the browser.
How do I cancel an in-flight fetch request?
Use the standard browser AbortController and pass its signal into the fetch options.
A100
API100 Engineering Team
Infrastructure & Latency Research

