← Back to all snippets
JAVASCRIPT

Securely Fetch Data from a REST API with Async/Await

Learn to safely fetch data from a REST API using modern JavaScript async/await syntax, including robust error handling and loading state management.

async function fetchData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            // Handle HTTP errors
            const errorData = await response.json().catch(() => ({ message: response.statusText }));
            throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorData.message || 'Unknown error'}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Error fetching data:", error);
        // Re-throw or return a specific error structure
        throw error;
    }
}

// Example usage:
async function getUserData() {
    try {
        const users = await fetchData('https://api.example.com/users');
        console.log('Users:', users);
    } catch (error) {
        console.error('Failed to get user data:', error.message);
    }
}

// Call the example function
// getUserData();
How it works: This snippet demonstrates how to fetch data from a REST API using JavaScript's `async/await` syntax for cleaner asynchronous code. It includes comprehensive error handling by checking `response.ok` for HTTP errors and catching network-related issues. The `fetchData` function can be reused across your application, providing a robust way to retrieve API information while managing potential failures.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs