JavaScript Async-Await API Handler for Serverless API Interactions
How can I create a reusable JavaScript API handler using async-await for serverless functions to make API calls more manageable and readable?
Here's a template for a reusable JavaScript API handler using async-await, designed for serverless environments. This approach enhances code readability and simplifies error handling when interacting with APIs.
try...catch blocks simplifies error management in asynchronous operations.
async function apiHandler(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('API call failed:', error);
throw error; // Re-throw to allow the caller to handle it
}
}
// Example usage:
async function fetchData() {
try {
const result = await apiHandler('https://api.example.com/data');
console.log('Data fetched:', result);
} catch (error) {
console.error('Failed to fetch data:', error);
}
}
fetchData();
apiHandler(url, options) Function:
options object (for method, headers, body, etc.).fetch with await to make the API request.response.ok). If not, throws an error.await response.json().fetch call in a try...catch block to handle network errors or API issues.fetchData function demonstrates how to use the apiHandler.apiHandler with the API endpoint.options object to include custom headers (e.g., authorization tokens).method in the options to 'POST', 'PUT', 'DELETE', etc.body in the options for POST or PUT requests, stringified as JSON.
async function postData(data) {
try {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
const result = await apiHandler('https://api.example.com/items', options);
console.log('Item created:', result);
} catch (error) {
console.error('Failed to create item:', error);
}
}
postData({ name: 'New Item', value: 123 });
This template provides a robust and readable way to handle API interactions in serverless JavaScript functions. By encapsulating the API call logic in a reusable function, you can maintain cleaner and more maintainable code.
Know the answer? Login to help.
Login to Answer